Reading Input File and Putting It Into An Array with Space Delimiter in Perl -


i trying take input file @argv array , write it's elements array delimiter space in perl.

sample input parameter txt file example:

0145 2145 4578 47896 45 78841 1249 24873 

(there multiple of lines here not shown) problem is:

  1. i not know how take example arg[0] array
  2. i want take every string of inputfile single strings in other words line1 0145 2145 not string 2 distinct string delimiting space.

i think want. @resultarray in code end holding list of digits.

if you're giving program file name use input command line, take off argv array , open filehandle:

my $filename = $argv[0]; open(my $filehandle, '<', $filename) or die "could not open $filename\n"; 

once have filehandle can loop on each line of file using while loop. chomp takes new line character off end of each line. use split split each line based on whitespace. returns array (@linearray in code) containing list of numbers within line. push line array on end of @resultarray.

my @resultarray; while(my $line = <$filehandle>){     chomp $line;     @linearray = split(" ", $line);     push(@resultarray, @linearray); } 

and remember add

use warnings; use strict; 

at top of perl file if problems in code.


just clarify how can deal different inputs program. following command:

perlfile.pl < inputfile.txt 

will take contents of inputfile.txt , pipe stdin filehandle. can use filehandle access contents of inputfile.txt

while(my $line = <stdin>){     # $line } 

but can give program number of file names read placing them after execution command:

perlfile.pl inputfile1.txt inputfile2.txt 

these file names read strings , placed @argv array array this:

@argv:     [0] => "inputfile1.txt"     [1] => "inputfile2.txt" 

since these names of files, need open file in perl before access file's contents. inputfile1.txt:

my $filename1 = shift(@argv); open(my $filehandle1, '<', $filename1) or die "can't open $filename1";  while(my $line = <$filehandle1>){     # line } 

note how i've used shift time next element within array @argv. see perldoc more details on shift. , more information on open.


Comments

Popular posts from this blog

jasper reports - Fixed header in Excel using JasperReports -

media player - Android: mediaplayer went away with unhandled events -

python - ('The SQL contains 0 parameter markers, but 50 parameters were supplied', 'HY000') or TypeError: 'tuple' object is not callable -