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

OO sub, hash or hash reference.

by IOrdy (Friar)
on Feb 18, 2002 at 15:04 UTC ( #146157=perlquestion: print w/replies, xml ) Need Help??

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

What I would like to do is be able to pass either a hash or a hash reference to my object method. And regardless of what is passed I would like it to end up as a hash reference. I searched here and damian's OOPerl book (which I'm not very far through) but couldn't find an example. I'm sure this is just a simple question (possibly redundant) but I cant figure it out and it's late at night.

Replies are listed 'Best First'.
Re: OO sub, hash or hash reference.
by dragonchild (Archbishop) on Feb 18, 2002 at 15:07 UTC
    There's a few ways you could do it. I'd do it as such:
    sub someMethod { my $self = shift; my $hashRef; if (UNIVERSAL::isa($_[0], 'HASH')) { $hashRef = shift; } else { $hashRef = { @_ }; } }
    Of course, you can add more checks and lots of cool stuff. But, that's basically the idea.

    We are the carpenters and bricklayers of the Information Age.

    Don't go borrowing trouble. For programmers, this means Worry only about what you need to implement.

      Out of curiosity, why the isa instead of a ref($_[0]) eq 'HASH'?

      Entropy is not what is used to be.
        after seeing the above code I did some reading:

        "The reason the original test is fragile ( ref($_[0]) eq 'HASH' ) is that it will make your code refuse to work on a hash if it happens to be blessed."

        It was simpler than I thought.
Re: OO sub, hash or hash reference.
by dash2 (Hermit) on Feb 18, 2002 at 16:57 UTC
    Assuming you aren't too bothered about blessed references, how about this?
    sub xxx { my $class = shift; my $args = ($#_ == 0) ? { %{ (shift) } } : { @_ };

    NB: not my own work.

    dave hj~

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (7)
As of 2023-01-30 10:49 GMT
Find Nodes?
    Voting Booth?

    No recent polls found