subr01 has asked for the wisdom of the Perl Monks concerning the following question:

If the file is: 1 http:/abcd efgh/ .. 2 http:/ .. I want one array to store 1 and 2. The second array should contain two elements having the two addresses. Since there is a space between address, using split function does not seem feasible. What should I do? This is my required output. $array[0] = 1 $array1 = 2 $arraynew[0] = http:/abcd efgh/ .. $arraynew1 = http:/ ..

Replies are listed 'Best First'.
Re: Reading file into two arrays
by hdb (Monsignor) on May 25, 2015 at 08:33 UTC

    There is a special variable $. that always contains the current line number of the file you are reading, starting with one. This can be used as the index for your two parallel arrays:

    use strict; use warnings; use Data::Dumper; my @array; my @arraynew; while(<DATA>){ chomp; ( $array[$.-1], $arraynew[$.-1] ) = split ' ', $_, 2; } print Dumper \@array, \@arraynew; __DATA__ 1 http:/abcd efgh/ 2 http:/

    Update 1: corrected split statement as per comments below.

    Update 2: another version based on regexes instead of using split:

    use strict; use warnings; use Data::Dumper; my @array; my @arraynew; ( $array[$.-1], $arraynew[$.-1] ) = /^(\S+)\s(.*)/ while <DATA>; print Dumper \@array, \@arraynew; __DATA__ 1 http:/abcd efgh/ 2 http:/

      This will work if
          ( $array[$.-1], $arraynew[$.-1] ) = split;
      is
          ( $array[$.-1], $arraynew[$.-1] ) = split ' ', $_, 2;
      (see below).


      Give a man a fish:  <%-(-(-(-<

Re: Reading file into two arrays
by aaron_baugher (Curate) on May 25, 2015 at 09:05 UTC

    split takes an optional third argument which says how many elements to split the string into, so it will work for your purposes:

    my $line = "1 http:/abcd efgh/"; my($number, $address) = split ' ', $line, 2; # $number now contains "1"; # $address now contains "http:/abcd efgh/";

    Aaron B.
    Available for small or large Perl jobs and *nix system administration; see my home node.