Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re: passing hashes and hash reference

by twerq (Deacon)
on Apr 20, 2001 at 21:03 UTC ( [id://74233]=note: print w/replies, xml ) Need Help??


in reply to passing hashes and hash reference

What you want to do is pass the hash reference to your sub, which expects a reference. Try:

sub myroutine { $hash_ref = (shift); $$hash_ref{foo}='bar'; } myroutine(\%thishash);


If you wanted to make sure you were getting a hash reference inside your sub, add a line like this:
die "Not a HASH reference" unless (ref($hash_ref) eq "HASH");

Replies are listed 'Best First'.
(tye)Re: passing hashes and hash reference
by tye (Sage) on Apr 20, 2001 at 21:19 UTC

    "HASH" eq ref($ref) is a fragile test and should be replaced with UNIVERSAL::isa($ref,"HASH").

    Update: The reason the original test is fragile is that it will make your code refuse to work on a hash if it happens to be blessed.

    Update2: Changed "HASH" eq ref to "HASH" eq ref($ref) to avoid confusion. Thanks, BMaximus.

            - tye (but my friends call me "Tye")
      Shouldn't that be: ref($hash) eq "HASH" ?
      Where $hash is a hashref?

      How about a bit more on why the UNIVERSAL::isa() method is better? I'm curious.

      BMaximus
      How about:
      sub rref { return UNIVERSAL::isa(@_); } if (rref($hash_ref,'HASH')) { # Wow! It's a hash! }
      UNIVERSAL is such a wacky thing. It's exactly the kind of direction that I would expect Parrot to take, but only if somehow Java were involved.
        *isa= \&UNIVERSAL::isa; if( isa($ref,"HASH") ) {

        works for me. (:

                - tye (but my friends call me "Tye")

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others scrutinizing the Monastery: (3)
As of 2024-06-24 19:29 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?
    erzuuli‥ 🛈The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.