First this behaviour is well documented in
perlsub ¹
And if it's not a frequent use case, please use two lines.
The next maintainer will be thankful to easily read how @v is defined:
my @v= keys %h;
die "Got extra Z: @v\n" if @v >1
Otherwise if you really need it that often, why don't you simply define a helper function?
DB<100> sub check { die "Got extra Z: @_\n" if @_ >1 }
DB<101> %h=(a=>1)
=> ("a", 1)
DB<102> check my @v= keys %h
=> ""
DB<103> %h=(a=>1,b=>2)
=> ("a", 1, "b", 2)
DB<104> check my @v= keys %h
Got extra Z: a b
And if you need more flexibility in testing, use some functional magic
DB<106> sub avoid (&;@) {
my $code=shift;
my $msg = $code->(@_);
die $msg if $msg;
}
DB<107> avoid { "Got extra Z: @_\n" if @_ >1 } my @v = keys %h;
Got extra Z: a b
DB<108> %h=(a=>1)
=> ("a", 1)
DB<109> avoid { "Got extra Z: @_\n" if @_ >1 } my @v = keys %h;
DB<110>
but again, for the sake of readability please use a line break
(even if it's a one liner)
avoid { "Got extra Z: @_\n" if @_ >1 }
my @v = keys %h;
And for completeness , I'm sure you could also use variable :attributes for such checks.
my @v :check = keys %h;
See Attribute::Handlers for details.
¹)
The declared variable is not introduced (is not visible) until
+after
the current statement. Thus,
my $x = $x;
can be used to initialize a new $x with the value of the old $x
+, and
the expression
my $x = 123 and $x == 123
is false unless the old $x happened to have the value 123.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.