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.

Cheers Rolf
(addicted to the Perl Programming Language and ☆☆☆☆ :)
Je suis Charlie!

¹)

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.

In reply to Re: Declaring with my, assigning, and testing in same line (custom routine) by LanX
in thread Declaring with my, assigning, and testing in same line by mordibity

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.