Reading the input file and transferring it to a space-delimited array in Perl

I am trying to take the input file with the @ARGV array and write all its elements to an array with dividing space in perl.

An example of an input parameter is a txt file, for example:

 0145 2145 4578 47896 45 78841 1249 24873 

(there are several lines, but not shown here) the problem is this:

  • I do not know how to take ARG [0] into an array
  • I want to take each line of this input file as single lines, in other words line 1 0145 2145 will not be a line, it will be two different lines, separated by a space.
+4
source share
1 answer

I think this is what you want. @resultarray in this code will contain a list of numbers.

If you give your program the name of the file that will be used as input from the command line, remove it from the ARGV array and open it as a file descriptor:

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

Once you have a file descriptor, you can iterate over each line of the file using a while loop. chomp this new line character from the end of each line. Use split to separate each line based on spaces. This returns an array ( @linearray in my code) containing a list of numbers inside this line. I then push my array of strings at the end of my @resultarray .

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

And don't forget to add

 use warnings; use strict; 

at the top of your perl file to help you if you run into problems with your code.


Just explain how you can work with the various inputs to your program. Next command:

 perlfile.pl < inputfile.txt 

Take the contents of the inputfile.txt file and pass it to the STDIN file descriptor. Then you can use this file descriptor to access the contents of inputfile.txt

 while(my $line = <STDIN>){ # do something with this $line } 

But you can also give your program several readable file names by placing them after the run command:

 perlfile.pl inputfile1.txt inputfile2.txt 

These file names will be read as strings and placed in the @ARGV array so that the array looks like this:

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

Since these are just file names, you need to open the file in perl before accessing the contents of the file. So for inputfile1.txt:

 my $filename1 = shift(@ARGV); open(my $filehandle1, '<', $filename1) or die "Can't open $filename1"; while(my $line = <$filehandle1>){ # do something with this line } 

Notice how I used shift this time to get the next element in the @ARGV array. See perldoc for details . As well as additional information about open .

+5
source

Source: https://habr.com/ru/post/1400835/


All Articles