http://www.perlmonks.org?node_id=476065


in reply to Re: Looking for syntactic shortcut
in thread Looking for syntactic shortcut

Ummm .... yes I did:
# perl -e "print localtime()[5]" syntax error at -e line 1, near ")[" Execution of -e aborted due to compilation errors.

Replies are listed 'Best First'.
Re^3: Looking for syntactic shortcut
by Thilosophy (Curate) on Jul 19, 2005 at 12:58 UTC
    I dont know about print, but assignment to a scalar works fine:
    perl -e 'print $a=(localtime())[5]' 105

    Update: Or, following BrowserUK:

    perl -e 'print +(localtime())[5]' 105

    Update: But not (in response to socketdave):

    perl -e 'print (localtime())[5]' syntax error at -e line 1, near ")[" Execution of -e aborted due to compilation errors.
    It seems we are hitting the finer points in the parser here...
Re^3: Looking for syntactic shortcut
by socketdave (Curate) on Jul 19, 2005 at 13:00 UTC
    look closer at Merlyn's example... you need '(localtime())[5]' instead of 'localtime()[5]'...
      Yes!

      The extra parens did the trick.

      Thank you all.

Re^3: Looking for syntactic shortcut
by gellyfish (Monsignor) on Jul 19, 2005 at 13:03 UTC

    Note that in your original post you had parentheses around the subroutine, these is also a slight gotcha in this example if you do:

    perl -e'print (localtime())[5]'
    as the parser takes the outer parentheses to be the argument list of the print which obviously can't be subscripted meaningfully, in this case you will want to use the no-op unary plus to disambiguate the context of the subscript:
    perl -e'print +(localtime())[5]'

    /J\

Re^3: Looking for syntactic shortcut
by rev_1318 (Chaplain) on Jul 19, 2005 at 13:01 UTC
    which should read:
    print +(localtime)[5]
    (note the + before the opening bracet, to prevent print from thinking it's his. When assigning to a variable, you say:
    my $year = (localtime)[5]
    just as you state in your own post :)

    Paul

Re^3: Looking for syntactic shortcut
by virtualsue (Vicar) on Jul 19, 2005 at 13:01 UTC
    That's not a very good test. Here's a very small program that does what you say you want:

    #!/usr/bin/perl use warnings; use strict; sub retarray { my $param = shift; my @array=(1,2,3,4,5,56); return @array; } my $param = 2; my $val = (retarray($param))[3]; print "val is $val\n";
Re^3: Looking for syntactic shortcut
by eyepopslikeamosquito (Archbishop) on Jul 19, 2005 at 13:02 UTC
    Try:
    perl -e "print((localtime)[5])"
    or:
    perl -e "print+(localtime)[5]"
    Quiz: can you explain why:
    perl -e "print (localtime)[5]"
    gives a syntax error?