On Mon, Feb 25, 2002 at 07:45:30PM +0100, Birgit Kellner wrote:
> Small question: I thought when doing a for loop over an array, I can simply 
> do this:
> for (@array) { # do stuff with $_ }
> 
> Now I have this situation:
> 
> for (@array) { # contains a bunch of numbers
>       my %hash = &get_record($_);
> }
> foreach (@array) { print "$_\n";\ # problem - $_ is not the array element 
> anymore
> 
> sub get_record {
> my $key = shift;
> my %hash;
> open (FILE, "<$file") || die ("can't open $file: $!");
> LINE: while (<FILE>) { my $line = $_; chomp ($line);

Here is your problem.

A while loop doesn't localise $_ as a for loop does.

See perlsyn for details.

> my @data = split/\|/, $line;
> if ($data[$db_key_pos] eq "$key") { # $db_key_pos is a global
>                       for (my $i = 0; $i <= $#db_cols; $i++) {  # Map the array 
>columns to a 
> hash. @db_cols is a global
>                               $rec{$db_cols[$i]} = $data[$i];
>                       }
>                       last LINE;
>               } # end if
> } #end while
> close DB;     
> return (%hash);
> }
> 
> The line commented with "problem" now has the last value of $line from the 
> subroutine get_record as $_, and no longer the original array element. Can 
> it be that the subroutine somehow assigns something else to $_ and that 
> this assignment is then taken over in the code from where it's called?

Exactly.

The solution is to add "local $_;" to the start of get_record.  This is
a good habit to get into for any sub which stomps on any glocal
variables.

-- 
Paul Johnson - [EMAIL PROTECTED]
http://www.pjcj.net

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to