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

In the following code:

use strict; use warnings; sub foo {return 'foo';} die "No bar here" if bar () ne 'bar'; print foo () . "\n"; print bar () . "\n"; sub bar {return 'bar';}

I get the following output:

Unquoted string "bar" may clash with future reserved word at noname.pl + line 8. foo Use of uninitialized value in concatenation (.) or string at noname.pl + line 8. print() on unopened filehandle bar at noname.pl line 8.

The text foo is sent to stdout, the remainder is sent to stderr. Note that the die isn't executed.

If I change the print bar to print '' . bar then I get the output I expect without error messages. What is going on here?


Perl is Huffman encoded by design.

Replies are listed 'Best First'.
Re: Wierd print and sub ordering problem
by rinceWind (Monsignor) on Oct 30, 2005 at 11:24 UTC

    Ah, you've hit the "print filehandle" parsing problem. Perl knows that foo is a sub as you have predeclared it. The problem with print bar () is that print will try to print the empty list to the filehandle bar.

    If you omit the space between bar and (), it will parse differently.

    --

    Oh Lord, won’t you burn me a Knoppix CD ?
    My friends all rate Windows, I must disagree.
    Your powers of persuasion will set them all free,
    So oh Lord, won’t you burn me a Knoppix CD ?
    (Missquoting Janis Joplin)

Re: Wierd print and sub ordering problem
by ioannis (Abbot) on Oct 30, 2005 at 12:01 UTC
    print bar () . "\n";

    Here, the word 'bar' is being interpreted as a filehandle.

    print +bar () . "\n";

    But with the + sign, the word 'bar' is now a term.