Hi all,
I thought I understood map however the following has results that I don't understand. I know why it's happening I just don't know how it is happening.
The problem is that the contents of @array are changing because $_
is being reset during _do_stuff_to_file
call. so what is printed is here: \nhere:\n
when I expect it to be here: donkie\nhere: kong\n
.
Note: This is not tested code. It's just what I remember seeing from lab. Why are the contents of @array
changing?
If I set $_
to $f
before returning 1 from _some_func
. Then the array is still intact.
Here is an example program to illustrate what I am seeing:
my @array = ("donkie", "kong");
map { push @junk, _some_func('blah', $_); } @array;
if (join ('', @junk) !~ /0/)
{ # for example sake this is always true since return 1 from _some_func.
print map { "here: $_\n"; } @array;
}
sub _some_func
{ # for example sake, lets say $f always exists as a file.
my $j = shift;
my $f = shift;
return 0 if !open(FILE, "< $f");
close FILE;
_do_stuff_to_file($f);
return 1;
}
sub _do_stuff_to_file
{
my $f = shift;
open(IN, "< $f");
open(OUT, "> $f.new");
while (<IN>)
{
print OUT;
}
close IN;
close OUT;
}