Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Passing values in a hash to a subroutine:

by Elihu (Novice)
on Feb 02, 2000 at 00:28 UTC ( #2674=perlquestion: print w/replies, xml ) Need Help??

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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://2674]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (4)
As of 2022-01-23 05:49 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    In 2022, my preferred method to securely store passwords is:












    Results (63 votes). Check out past polls.

    Notices?