in reply to Looking for syntactic shortcut

Only I want to do it shorter. Something like:
$elem = (function($param))[5]
which obviously doesn't work.
No falser words have been spoken. {grin}

Did you try it? It works just fine. It's precisely why I invented that notation in the first place (for Perl version 3).

-- Randal L. Schwartz, Perl hacker
Be sure to read my standard disclaimer if this is a reply.

Replies are listed 'Best First'.
Re^2: Looking for syntactic shortcut
by mrd (Beadle) on Jul 19, 2005 at 12:55 UTC
    Ummm .... yes I did:
    # perl -e "print localtime()[5]" syntax error at -e line 1, near ")[" Execution of -e aborted due to compilation errors.
      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...
      look closer at Merlyn's example... you need '(localtime())[5]' instead of 'localtime()[5]'...
        Yes!

        The extra parens did the trick.

        Thank you all.

      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\

      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

      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";
      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?