Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

what is keys %$hash_ref [-1]

by Anonymous Monk
on Apr 27, 2011 at 18:30 UTC ( #901625=perlquestion: print w/ replies, xml ) Need Help??
Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Dear Monks

The question is in the title :) What is
keys %$hash_ref [-1]
I understand the keys and dereferencing the hash ref but what is the -1 doing? In the code this is from, the resulting list from the keys function is passed into a map function

thanks

Comment on what is keys %$hash_ref [-1]
Download Code
Re: what is keys %$hash_ref [-1]
by wind (Priest) on Apr 27, 2011 at 18:39 UTC
    It's a syntax error. Is there more of the code?
Re: what is keys %$hash_ref [-1]
by Anonymous Monk on Apr 27, 2011 at 18:39 UTC
    It is syntax error
Re: what is keys %$hash_ref [-1]
by philipbailey (Chaplain) on Apr 27, 2011 at 19:17 UTC

    The fragment you have shown will not compile. The following will compile:

    (keys %$hash_ref)[-1]

    ... and will return the "last" key of hash %$hash_ref. But that would seem somewhat meaningless, as the keys of a hash do not have any specific order. Any apparent order of the keys may change when the elements of the hash are changed, or a different Perl is used.

Re: what is keys %$hash_ref [-1]
by ikegami (Pope) on Apr 27, 2011 at 19:18 UTC

    Did you perhaps mean (...)[-1]?

    That's a list slice. The expression in the parens is evaluated in list context. The expression in the square brackets must return a list of indexes. The slice returns the elements of the returned list identified by the indexes. Negative indexes are relative to the end of the list, where -1 is the last element of the list.

    ( grep { $_ % 4 == 0 } 1..10 ) )[-1] # The last num divisible by 4.
Re: what is keys %$hash_ref [-1]
by AnomalousMonk (Abbot) on Apr 27, 2011 at 22:52 UTC

    Here's another guess along the lines of "Maybe if I add some more stuff, it'll be a valid statement":

    >perl -wMstrict -le "my @hash_ref = ({ qw(a 1 b 2) }, { qw(c 3 d 4) }); ;; print keys %{ $hash_ref [-1] }; print values %{ $hash_ref [-2] }; " cd 12
Re: what is keys %$hash_ref [-1]
by Anonymous Monk on Apr 28, 2011 at 07:43 UTC
    What would be the purpose of getting the last element of a list without sorting the keys (in a corrected statement as shown in other replies)? (OTOH, the original correct code just might have sort in there too.)

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (10)
As of 2014-10-22 12:51 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    For retirement, I am banking on:










    Results (118 votes), past polls