How can I retrieve data loaded into an array within a foreach block?
The array is defined outside the foreach block and is not the indexing
array of the foreach loop.
I have defined three arrays
my @lines = ();
my @line = ();
my @lastnames = ();
loaded into @lines a file in which each line is a series of tab
separated items and run the following code using warnings and strict
foreach (@lines) {
@line = split /\t/, $_;
push @lastnames, $line[2];
}
This works perfectly BUT when I try to uses @lastnames I get a warning
that it is undefined. Specifically, I continued
@lastnames = sort @lastnames;
my $dup = "";
foreach (@lastnames) {
if ($dup ne $_) {
print $_;
$dup = $_;
}
}
and still everything works but there is a warning the $_ is undefined in
the condition statement.
I don't understand why it should not be possible to modify a global
variable inside the foreach loop. In the second part of the problem I
modified the code as follows
my $dup = "";
my $item = "NoName";
foreach (@lastnames) {
$item = $_;
if ($dup ne $item) {
print $item;
$dup = $item;
}
}
reasoning that foreach might be treating $_ like a numeral though it
actually holds current name from the array @lastnames. Now I received a
warning that $item was undefined in the conditional statement.
I hope there is a straightforward way of correctly doing what this code
does and I realy would like to understand why it is incorrect.
Tom
--
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
http://learn.perl.org/