Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re^3: referances of hashes, and subroutines

by zer (Deacon)
on Apr 22, 2006 at 20:25 UTC ( [id://545083]=note: print w/replies, xml ) Need Help??


in reply to Re^2: referances of hashes, and subroutines
in thread referances of hashes, and subroutines

it isnt as much magical as it is prototyping.
use strict; use warnings; my %list=("bob" =>123, "tom" => "CAT"); sub change(\%){ my $temp = shift; foreach (keys %$temp){ print $_. " = $$temp{$_}\n"; $$temp{$_} .= "hello"; } } change (%list); foreach (keys %list){ print "$_ = $list{$_}\n"; }
declaring the subroutine as sub change(\%){ will send the values as a reference

Replies are listed 'Best First'.
Re^4: referances of hashes, and subroutines
by GrandFather (Saint) on Apr 22, 2006 at 20:35 UTC

    It's magical to the extent that prototypeing is generally frowned on so is one of the lesser known corners of Perl.

    It is also magical in that the local context doesn't provide enough information to understand that there may be side effects when calling the sub. That is dangerous magic. Passing a reference to a sub explicitely is a strong hint that the referent will be altered.


    DWIM is Perl's answer to Gödel
      And by the way, it's nice to do a favor for yourself within the subroutine that's receiving the reference to name the variable with a little suffix that implies that the scalar variable is not just a number or a string but that it is a REFERENCE flavor of scalar! e.g.

      use strict; my %hash = qw( abc xyz ); print "Hash key(s) are:\n"; print "$_\n" foreach my_sub( \%hash ); sub my_sub { my ( $hash_hr ) = @_; return ( keys %$hash_hr ); }
      In this case, since passing a hash reference, my suffix is 'hr'. If it was an array reference, I'd tack on '_ar'. The suffix does nothing to guarantee that what's in that scalar variable is really an array reference or a hash reference, but it sure makes reading over the code later easier when you are trying to remember what each variable is supposed to be doing and how it is built.

      By the way, even though only one argument is being passed, I like my subroutines to receive them from @_ via list context since it makes it easier to grow/evolve the subroutine later on. Same for passing return values....

Re^4: referances of hashes, and subroutines
by tempest (Sexton) on Apr 22, 2006 at 20:30 UTC
    thanks! This works.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (5)
As of 2024-04-25 11:46 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found