Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

function input may be hash ref

by Anonymous Monk
on Mar 14, 2013 at 18:24 UTC ( #1023522=perlquestion: print w/ replies, xml ) Need Help??
Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I'm maintaining code that was handling only numerical inputs. Now the input may be a hash reference or a number. How can I filter out the hash reference inputs? My code is sort of like this now:

if ($val =~ /^([\d]+)\'[b]([01]+)$/) { $strlen = $1; my $binstr = $2; #do things ... } else { print "Wrong kind of input"; }

Comment on function input may be hash ref
Download Code
Re: function input may be hash ref
by toolic (Chancellor) on Mar 14, 2013 at 18:35 UTC
Re: function input may be hash ref
by tobyink (Abbot) on Mar 14, 2013 at 18:36 UTC
    if (ref $val eq "HASH") { ... }

    or if you wish to also accept values that are "hashref-like" (e.g. blessed hashrefs, objects overloading %{}), then:

    use Scalar::Does; if (does $val, "HASH") { ... }
    package Cow { use Moo; has name => (is => 'lazy', default => sub { 'Mooington' }) } say Cow->new->name
Re: function input may be hash ref
by arnaud99 (Beadle) on Mar 14, 2013 at 18:52 UTC

    Hi

    Using ref to filter out the references you do no wish to process.

    use Modern::Perl; my $array_ref = ["12'b01", "1333'b011111"]; my @vals = ( "12'b01", "1333'b011111", $array_ref, # one array ref; "aa'b01", "12'b01", { a=>1 }, #hash ref {}, # another hash ref [ "12'b01", "1333'b011111"], #another array ref "12'b01", ); foreach my $val(@vals) { if (ref $val eq 'ARRAY' or ref $val eq 'HASH' ) { say "This is an array or hash ref: Don't process", } elsif ($val =~ /^([\d]+)\'[b]([01]+)$/) { my $strlen = $1; my $binstr = $2; #do things ... say "Found: ", $strlen, ", ", $binstr; } else { say "Wrong kind of input: $val"; } }

    Output

    Found: 12, 01 Found: 1333, 011111 This is an array or hash ref: Don't process Wrong kind of input: aa'b01 Found: 12, 01 This is an array or hash ref: Don't process This is an array or hash ref: Don't process This is an array or hash ref: Don't process Found: 12, 01

    Arnaud.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (14)
As of 2014-08-27 22:58 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (253 votes), past polls