$name getting changed to $_

B

Brian

I am stumped here - Can someone look at my code and tell me why my
$name variable is being changed to what is stored in $_? Thx.

foreach(@name) {
if ($files[$x] ne "") {

open SETI, $files[$x] or die "Can not open $files[$x] :$!";
print "name after open = @name\n";
while (<SETI>) {
### $name actually changes here - moved it for readability
if ($. eq 39) {
print "Default Input = $_\n";
print "name after if = @name\n";
chomp;

/(\d.) hr (\d.)/;
$Avg_Time[$x] = $1*60+$2;

}
}
$x++;
close SETI;
}
}

Please let me know if you need any more information.
Thx - Brian.
 
J

Jeff 'japhy' Pinyan

[posted & mailed]

I am stumped here - Can someone look at my code and tell me why my
$name variable is being changed to what is stored in $_? Thx.

foreach(@name) { [snip]
while (<SETI>) {

That's why.

When you do a for-loop on an array like that, the variable you use to
iterate over the array (by default, $_) is *aliased* to the element you're
working on:

@stuff = (1, 2, 3);
for (@stuff) { $_ += 5 }
print "@stuff"; # 6 7 8

That is, changes done to $_ effect the element in the array.

Additionally, when you use a while loop on a filehandle, if you don't
specify a variable, $_ is used. The problem is that it's the SAME $_
you happen to be using to iterate over your array.

while (<FILE>)
# is actually
while (defined($_ = <FILE>))

So, change at least ONE of those loops.

for my $n (@name) { ... }

while (my $line = <FILE>) { ... }

like so.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,535
Members
45,007
Latest member
obedient dusk

Latest Threads

Top