in reply to Store the outcome of a foreach loop in an array

I second what ++LanX said. But also, if the for loop is only going once, then @$lines only has one element. Are you sure $lines is an array-ref? Or did you really mean foreach my $line (@lines)?

Replies are listed 'Best First'.
Re^2: Store the outcome of a foreach loop in an array
by perl_5eeker (Novice) on Jan 10, 2019 at 22:39 UTC

    If I print "@$lines", I get this:

    c1r1,c2r1,c3r1,c4r1,c5r1 c1r2,c2r2,c3r2,c4r2,c5r2 c1r3,c2r3,c3r3,c4r3,c5r3
    I was trying to store "c3r1 c3r2 c3r3" in "@store" - but it only saves "c3r1" and comes out of the loop :(

      but it only saves "c3r1" and comes out of the loop

      This would happen if @$lines only has a single element, "c1r1,c2r1,c3r1,c4r1,c5r1\nc1r2,c2r2,c3r2,c4r2,c5r2\nc1r3,c2r3,c3r3,c4r3,c5r3". As I showed here, please use Data::Dumper to print out $lines, as in: "use Data::Dumper; $Data::Dumper::Useqq=1; print Dumper($lines);". If that shows a single string with \n's in it, then my assumption is correct. Instead of doing something like using split on that string, it's probably better if we took a look at where you're getting $lines from - please have a look at Short, Self-Contained, Correct Example, a SSCCE would be useful so we can run the code for ourselves and see exactly the issue you're having.

        Here is SSCCE

        #!/usr/bin/perl use customlib; my $file = 'cr.csv'; my $lines; rdfile($file,\$lines); # Remove comments and blank lines @$lines = grep(!/^\s*#/,@$lines); @$lines = grep(!/^\s*$/,@$lines); @$lines = join "\n", @$lines; my @store; foreach my $line (@$lines) { my @val = split(/\,/,$line); push (@store,$val[2]); } #printf "@store\n"; use Data::Dumper; $Data::Dumper::Useqq=1; print Dumper($lines);
        And you were right - @$lines with Data::Dumper printed the following output: $VAR1 = "c1r1,c2r1,c3r1,c4r1,c5r1\nc1r2,c2r2,c3r2,c4r2,c5r2\nc1r3,c2r3,c3r3,c4r3,c5r3" ;

      Are you sure you showed us all the code?

      Cheers Rolf
      (addicted to the Perl Programming Language :)
      Wikisyntax for the Monastery FootballPerl is like chess, only without the dice