in reply to Array reference

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.

Replies are listed 'Best First'.
Re^2: Array reference
by Anonymous Monk on Jun 09, 2011 at 12:22 UTC
    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 }
        Thank you very much moritz, I did not dare write a subroutine yet. I have learned a lot today.
      @Result = (); # should empty your array for you.
Re^2: Array reference
by Anonymous Monk on Jun 09, 2011 at 12:48 UTC
    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).