Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

using constants

by Hena (Friar)
on Oct 13, 2005 at 05:48 UTC ( [id://499769]=perlquestion: print w/replies, xml ) Need Help??

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

Hello Monks, I'm using some strings in a scripts as constants as they are strings used in parsing of file. But I've noticed a small oddity on this. So is this expected (couldn't find any reference in camel book on this).
> perl -we 'use constant K => 0;$array[0]="value";print $array[K],"\n" +;' value > perl -we 'use constant K => KEY;$hash{"KEY"}="value";print $hash{K}, +"\n";' Use of uninitialized value in print at -e line 1.
The array works as I expected. The hash does not. Is it better to use scalar even though it is not constant (used to do these that way)?

Replies are listed 'Best First'.
Re: using constants
by ikegami (Patriarch) on Oct 13, 2005 at 05:51 UTC

    The quotes are optional on barewords used as hash elements.
    $hash{key} is the same as $hash{'key'}
    $hash{shift} is the same as $hash{'shift'}
    $hash{K} is the same as $hash{'K'}

    Use
    $hash{K()},
    $hash{&K},
    $hash{(K)} or
    $hash{+K}
    to work around the autoquoting.

    Update: I thought I'd add a link to the relevant documentation, but I can't find documentation on this. perldata mentioned the auto-quoting property of =>, but not of the hash index.

      Ah, Thanks. I Should have realised that :). Btw. Whats that + do? I understand the braces and &.

        This question is in the docs. Specifically, perlop.

        Unary-+ does nothing, but where XXX is a bareword, +XXX and (XXX) are expressions. Only barewords are auto-quoted, not expressions.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://499769]
Approved by ikegami
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others about the Monastery: (5)
As of 2024-03-29 10:34 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found