SPUG:Best One-Liners and Scripts for UNIX

Yitzchak Scott-Thoennes sthoenna at efn.org
Tue Apr 29 19:41:57 CDT 2003


On Tue, 29 Apr 2003 10:25:26 -0700, tim at consultix-inc.com wrote:
>On Sat, Apr 26, 2003 at 10:49:17PM -0700, Yitzchak Scott-Thoennes wrote:
>> On Sat, 19 Apr 2003 10:37:13 -0700, tim at consultix-inc.com wrote:
>> >        ($fields = shift) =~ /^[\d,.]+$/g or
>> 
>> That trips a warning if the script is given no args.  Make it:
>> $fields = shift and $fields =~ ... 
>
>Good idea, but that's not the same, because they could ask for field
>#0 only, and that would be treated the same as a missing argument due
>to its false value. I can't see the original program I submitted at
>the moment, but I would usually have had a "@ARGV > 0 or die" or
>equivalent in the BEGIN block to handle this kind of argument checking.

Sorry, I snipped too much of your code.  The line I quote is the
"@ARGV > 0 or die" equivalent.  And you adjust @F so that field 1 is
the first field.  However, if field 0 were allowed, you could say:

        defined($fields = shift) and $fields =~ /^[\d,.]+$/g or
                die "Usage: $0 '2,1,3,4..7' [ file ... ]";

or use the completely imaginary C<dand> operator :)

        $fields = shift dand $fields =~ ...

>> The parens there aren't necessary.  You need parens for something
>
>I wasn't writing for the benefit of the compiler, but for that of the
>reader, who I think will find it easier to understand that a list is
>being formed with the parens there (and they don't bother the compiler).

It's the illusion that () creates a list that I find objectionable.

>> like: @fields = (5,2..4) just for correct precedence ('=' is lower
>> precedence than ','), but with the eval there, there is no precedence
>> problem.  Parens almost never affect anything besides precedence.
>> (Two major exceptions are around the left operands of '=' and 'x':
>> there the behaviour of the operator completely changes.  I thought
>
>But my parens *are* on the right side of an "=", so if one glosses
>over the eval, it reads like @fields = ( 5,2..4 ).  That was my
>intention, anyway; obviously, you know too much about Perl to appreciate
>this illusion! 8-}

Here are some fun things to try:
sub context { print wantarray ? "list" : defined wantarray ? "scalar" : "void" }
$x = context;   # scalar context
$x = (context); # still scalar context, () on right have no effect
($x) = context; # list context, () on left force list context on right
($x) = (context); # still list context, () on right have no effect
@x = context;   # list context
$x ? ($x) : ($x) = context; # if ?: on left, check its 2nd & 3rd operands for ()



More information about the spug-list mailing list