Hi,
I want to use a foreach loop to iterate over a list but I want to be able to
retain the index variable when the loop ends (either at the end of the list
or by an early-exit "last" statement).
Given the following example code:
#!/usr/bin/perl -w
use strict;
my %hash = ( "one" => {}, ## This part isn't important for this example
"two" => {},
"three" => {},
);
## code to populate %hash subhashes goes here...
foreach my $elem (@long_list) {
my $k="junk";
foreach $k (keys %hash) {
last if($elem =~ /$k/); ## ok, I've got the $k I need
}
$hash{$k}->{'foo'} = 42; ## oops, $k is reset to "junk"
}
I guess I need to assign $k to some other variable that will be visible
outside of the foreach loop before I call "last"...
but I want it to look nice too :) and that's the problem.
my $bar;
foreach $k (keys %hash) {
if($elem =~ /$k/) {
$bar = $k; ## can't I do better than this?
last;
}
}
Ok, so it's not much of a problem but is there a way to get the nice feel of
the one-line "last if(..." and still do the assignment operation to retain
the value of $k?
Or, is there any way to get around the way foreach localizes the index
variable?
Thanks.
-- Brad
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]