Elihu has asked for the wisdom of the Perl Monks concerning the following question:

I'm trying to clean up data in a hash by passing the values to a subroutine. I'm using a foreach loop as follows:
foreach $key (keys (%hash)) { replace ($hash{$key}); }
I would expect this code to work, but it doesn't. I've tried explicitly using $_, also:
sub replace { chomp; s/'/\\'/g; }
This one works:
sub replace { chomp $_[0]; $_[0] =~ s/'/\\'/g; }
Could anyone explain this to me? -Thanks.

Replies are listed 'Best First'.
Re: Passing values in a hash to a subroutine:
by Anonymous Monk on Feb 02, 2000 at 00:49 UTC
    in subroutines, @_ is the array of arguments passed to the subroutine -- $_ is not related to @_ -- specificly,
    $_ isn't $_[0] $_[0] is the first element of @_ Compare to $a, @a, and $a[0]
    Does this make sense?
RE: Passing values in a hash to a subroutine:
by Anonymous Monk on Feb 02, 2000 at 01:00 UTC
    In the first version you are manipulating $_, but you haven't set $_ to any value. you seem to thing that it will be set to each of your hash keys in turn, there's no code to make tha happen. In the second version, you're manipulating the first element of @_, which _is_ set to each key in turn. Therefore it works! hth, davorg...
Re: Passing values in a hash to a subroutine:
by Elihu (Novice) on Feb 02, 2000 at 03:34 UTC
    I just tried throwing a shift statement before the chomp statement in the first sub replace block. And even though this has the effect of taking the first element of @_ and placing it in $_, the changes don't make it back to the hash.

    After reading 'the gory details', I found that this is because @_ is an implicit reference to the actual scalar parameters, and therefore the modifications made upon @_ make it back to my hash. But if I shift the value into $_, any changes I make won't make it back to my hash.

    Is this correct? Thanks for the help.