Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask

Re: What does the dash before hash assignment means?

by kcott (Chancellor)
on Sep 03, 2013 at 21:02 UTC ( #1052180=note: print w/replies, xml ) Need Help??

in reply to What does the dash before hash assignment means?

G'day anaconda_wly,

"I saw some perl code with a dash before key name for hash assignment. Any special meaning? Does that equal to a quotation mark? Thanks for any help. fun(-url => $httpRefer);"

Firstly, let's look at how Perl parses that (with and without the dash):

$ perl -MO=Deparse,-p -e 'fun(-url => $httpRefer);' fun((-'url'), $httpRefer); -e syntax OK $ perl -MO=Deparse,-p -e 'fun(url => $httpRefer);' fun('url', $httpRefer); -e syntax OK

So, clearly something special is happening. Is it the dash or the fat comma?

$ perl -MO=Deparse,-p -e 'fun(-url);' fun((-'url')); -e syntax OK

No fat comma and we're still getting "-url" parsed as "(-'url')". This indicates that the dash is the cause; the perlop: Symbolic Unary Operators documentation bears this out:

"If the operand is an identifier, a string consisting of a minus sign concatenated with the identifier is returned."

Without actually looking at the parsing process, you could have run some simple tests:

$ perl -Mstrict -Mwarnings -le ' sub fun { print "@_" } fun(1, url); fun(2, -url); fun(3, -url, "httpRefer"); fun(4, -url => "httpRefer"); fun(5, url, "httpRefer"); fun(6, url => "httpRefer"); ' Bareword "url" not allowed while "strict subs" in use at -e line 3. Bareword "url" allowed while "strict subs" in use at -e line 7. Execution of -e aborted due to compilation errors.

Commenting out the lines with barewords:

$ perl -Mstrict -Mwarnings -le ' sub fun { print "@_" } #fun(1, url); fun(2, -url); fun(3, -url, "httpRefer"); fun(4, -url => "httpRefer"); #fun(5, url, "httpRefer"); fun(6, url => "httpRefer"); ' 2 -url 3 -url httpRefer 4 -url httpRefer 6 url httpRefer

While I can see that "(-url => $httpRefer)" might be used as a key/value pair in some hash assignment, you don't actually show any code performing such an operation. [If you thought you did, you may need to ask another question :-)] Regardless, the code I've posted here involves no hashes at all: the unary minus operator, in this context, is unrelated to hashes!

-- Ken

Replies are listed 'Best First'.
Re^2: What does the dash before hash assignment means?
by anaconda_wly (Scribe) on Sep 04, 2013 at 08:05 UTC
    thanks everyone! I see.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1052180]
[LanX]: often sounds like Low German

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (7)
As of 2018-04-23 10:45 GMT
Find Nodes?
    Voting Booth?