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

Dear Monks, I am very new in Perl, please excuse me if it is a dumb question. This code:
use 5.010; use strict; use warnings; my $Outcome; while (<DATA>) { my @Result = (); next unless $_ =~/\d+\schunk/; s/\s+/ /g; push @Result, $_."\n"; $Outcome = \@Result; print "@$Outcome"; } print "X\n"; #debug print "@$Outcome"; __DATA__ Free text. Free text. Blah Blah Blah Transaction XXX Apple 28 chunk Pear 140 chunk cherry 231 chunk potato 1 chunk Sincerely Yours
The first print @$Outcome shows all the lines, the second one print @$Outcome shows only line with potato. Where is my mistake? Thank you! GH

Replies are listed 'Best First'.
Re: Array reference
by moritz (Cardinal) on Jun 09, 2011 at 12:03 UTC

    Since you have my @Result inside the loop, each iteration of the use creates a new @Result variable, which holds at most one item at the end of each iteration, because you push at most one line to it in each iteration.

    $Outcome is a reference to the last of the arrays you create.

    I guess what you actually want is to move the my @Result outside of the loop.

    Also there's no reason for initializing the new array with () - my gives you a perfectly fine empty array already.

    See also: Coping with Scoping.

      Thank you moritz, actually I have many text files which I want to work through. My idea was, to process each file per loop with the same array and then to save the outcome (per reference) in different files. I have just tried it with my @Result declaration at the beginning i.e. above the loop. It works now! But: how can I empty this array if I start processing the next file? Thank you!

        Typically you would do something like this:

        for my $filename (@list_of_file_names) { process_file($filename); } sub process_file { my $filename = shift; open my $handle, '<', $filename or die "Can't open file '$filename' for reading: $!"; my @Result; while(<$handle>) { next unless $_ =~/\d+\schunk/; s/\s+/ /g; push @Result, $_."\n"; } # do something interesting with @Result here }
        @Result = (); # should empty your array for you.
      Here am I again. I put @Result = () in the outer loop (here not showed), direct after foreach my $file(@files), now it works too (i.e. the array empties).