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

I am trying to take an input file with @ARGV array and write it's all elements to an Array with delimiter space in perl.

sample input parameter is a txt file for example:

0145 2145
4578 47896
45 78841
1249 24873

(there are multiple of lines but here it is not shown) the problem is:

  1. I do not know how to take for example ARG[0] to an array
  2. I want to take every string of that inputfile as single strings in other words the line1 0145 2145 will not be a string it will be two distinct string by delimiting with space.

Upvotes: 4

Views: 19314

Answers (1)

MattLBeck
MattLBeck

Reputation: 5831

I think this is what you want. The @resultarray in this code will end up holding a list of digits.

If you're giving your program a file name to use as input from the command line, take it off the ARGV array and open it as a filehandle:

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

Once you have the filehandle you can loop over each line of the file using a while loop. chomp takes that new line character off the end of each line. Use split to split each line up based on whitespace. This returns an array (@linearray in my code) containing a list of the numbers within that line. I then push my line array on to the end of my @resultarray.

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

And remember to add

use warnings;
use strict;

at the top of your perl file to help you if you get any problems in your code.


Just to clarify how you can deal with different inputs to your program. The following command:

perlfile.pl < inputfile.txt

Will take the contents of inputfile.txt and pipe it to the STDIN filehandle. You can then use this filehandle to access the contents of inputfile.txt

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

But you can also give your program a number of file names to read by placing them after the execution command:

perlfile.pl inputfile1.txt inputfile2.txt

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

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

Since these are just the names of files, you need to open the file in perl before you access the file's contents. 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
}

Note how I've used shift this time to get the next element within the array @ARGV. See the perldoc for more details on shift. And also more information on open.

Upvotes: 6

Related Questions