bsdz has asked for the wisdom of the Perl Monks concerning the following question:

I often need to print an element from a function like stat or localtime. I am curious, since a line like: -
print "".(localtime)[2]."\n"
for example works, but a line like this will return a syntax error: -
print (localtime)[2]."\n"
Is there documentation on this notation and/or why this syntax is wrong?

Replies are listed 'Best First'.
Re: print list element from function syntax
by Hofmator (Curate) on Jun 25, 2004 at 13:05 UTC
    What happens is that perl interprets this as
    print(localtime) # call print with one argument: whatever is returne +d by localtime [2]."\n"
    and then perl doesn't know what to do with the [2] after the print statement.

    To fix this, simply write print +(localtime)[2]."\n";

    -- Hofmator

Re: print list element from function syntax
by japhy (Canon) on Jun 25, 2004 at 12:57 UTC
    Well, the warning you'd get if you had warnings enabled explains what's wrong, although I'm pretty sure Abigail-II found some problems with the heuristic Perl uses in this case. Basically, generally, if a function name is followed by a SINGLE space and then parentheses, Perl lets you know that your attempt to not put parentheses around the arguments to a function failed. But if you add another space, you don't get the warning. If you remove the space, you don't get the warning. (You always get the error, though.)
    _____________________________________________________
    Jeff[japhy]Pinyan: Perl, regex, and perl hacker, who'd like a job (NYC-area)
    s++=END;++y(;-P)}y js++=;shajsj<++y(p-q)}?print:??;
Re: print list element from function syntax
by PodMaster (Abbot) on Jun 25, 2004 at 12:56 UTC
    Yup, see gory details of parsing quoted constructs. try perlsyn
    To perl, it looks like you maybe want to print( something ) but it can't decide
    C:\>perl -MO=Deparse,-p print (localtime)[2]."\n" __END__ syntax error at - line 1, near ")[" - had compilation errors. ; C:\>perl -MO=Deparse,-p print "".(localtime)[2]."\n" __END__ print((('' . (localtime)[2]) . "\n")); - syntax OK
    update: I stuck some stuff out (doesn't apply). Try print ( (localtime)[2], "\n" ). Then edited some (i really rushed on this one).

    MJD says "you can't just make shit up and expect the computer to know what you mean, retardo!"
    I run a Win32 PPM repository for perl 5.6.x and 5.8.x -- I take requests (README).
    ** The third rule of perl club is a statement of fact: pod is sexy.

Re: print list element from function syntax
by Anonymous Monk on Jun 25, 2004 at 12:50 UTC
    Not an expert on this but its something to do with doing to things at once. Geting a return from a function and the trying to take a element from the return. This works
    print ((localtime)[2])."\n"
      It kind of works but seems to ignore the newline character!