Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change

Parenthetical help

by eye (Chaplain)
on Apr 03, 2011 at 14:35 UTC ( #897195=perlquestion: print w/replies, xml ) Need Help??
eye has asked for the wisdom of the Perl Monks concerning the following question:

In the following code snippet, I don't understand why Perl 5.8.8 says there is a syntax error near ")[" at #3.

#!/usr/bin/perl use strict; use warnings; my $t = (time)[0]; #1 my @t = localtime $t; @t = localtime ((time)[0]); #2 @t = localtime (time)[0]; #3

If I comment out #3, both #1 & #2 correctly populate @t. It just seems as though the outer parentheses in #2 should not be needed.


Replies are listed 'Best First'.
Re: Parenthetical help
by Corion (Pope) on Apr 03, 2011 at 15:00 UTC

    Perl sees #3 as

    @t = localtime(time)

    but then encounters


    ... which doesn't make sense to Perl, which means it raises a syntax error.

      Thanks! Much appreciated.
Re: Parenthetical help
by jwkrahn (Monsignor) on Apr 03, 2011 at 17:55 UTC

    BTW, all three are wrong as time always returns a scalar so using a list slice on it makes no sense.

      Good point. The code I posted was oversimplified to isolate the issue. The original code was getting the modify time of a file and looked more like:

      localtime((stat $file)[9])

        The problem is that localtime has a prototype and that prototype says that localtime's first argument, if present, must be a scalar value, so arrays and lists are converted to a scalar value so localtime can use it.

        $ perl -le'print prototype "CORE::localtime"' ;$
Re: Parenthetical help
by wind (Priest) on Apr 03, 2011 at 18:37 UTC