Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much

Smart matching for argument constraints

by LanX (Chancellor)
on Sep 03, 2012 at 13:45 UTC ( #991434=perlquestion: print w/replies, xml ) Need Help??
LanX has asked for the wisdom of the Perl Monks concerning the following question:


I'm considering using the smart macht operator for argument constraints at the start of a sub.

I have to admit that ~~ still confuses me a lot

is the following code correct to check if

1. the argument is a simple scalar (that is no ref) 2. and element of the given set (here a b c)?

sub tst { %arg = @_; warn "wrong argument" unless "$arg{x}" ~~ [qw/a b c/] ; }

so e.g. tst(x => "a"); is ok.

the explicit stringification (quotes) of "$arg{x}" is necessary to avoid tst(x => [qw/a b c/]); to be legal.

Any comments? Any better idioms for checking arguments?

Cheers Rolf

Replies are listed 'Best First'.
Re: Smart matching for argument constraints
by mithaldu (Monk) on Sep 03, 2012 at 14:30 UTC
      Thanks, this reflects my general suspicion towards smart matching...!

      Cheers Rolf

Re: Smart matching for argument constraints
by tobyink (Abbot) on Sep 04, 2012 at 06:53 UTC

    Personally I'd make the intent a little more obvious:

    warn "wrong argument" if ref $arg{x} || !($arg{x} ~~ [qw/a b c/]);
    perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://991434]
Approved by Athanasius
[dazz]: Hi I have grabbed an image from an IP camera with Image::Grab. I then want to pass that image object to a subroutine where I do a read-only test on the image with Image:Magick.
[dazz]: How do I pass an image object to a subroutine and then apply a Image::Magick a read-only method to the image object???
[dazz]: Also, I want to use Image::Magick to annotate and composite (not in a sub). How do I take a Image::Grab object and apply Image::Magick write methods to it??

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (7)
As of 2017-03-27 07:38 GMT
Find Nodes?
    Voting Booth?
    Should Pluto Get Its Planethood Back?

    Results (317 votes). Check out past polls.