http://qs1969.pair.com?node_id=11134447


in reply to Re: Using 'keys' on a list
in thread Using 'keys' on a list

Thanks for the response =).
keys doesn't operate on a list
Do you know why this might be? Maybe because strictly speaking, only hashes have keys, and lists don't? But then perl isn't usually that strict e.g. as you mentioned from 5.12 keys can operate on an array. I ask because I was hoping to be able to do this in one line. It's not a big deal but I'm kind of curious to see if it's possible.

Replies are listed 'Best First'.
Re^3: Using 'keys' on a list
by choroba (Cardinal) on Jun 29, 2021 at 15:13 UTC
    > Do you know why this might be?

    Lists don't have keys. For arrays, keys returns the indices of the elements, not every second element. So, given a list, should keys use the hash semantics or the array one?

    Also note that a "list" in fact doesn't exist in Perl. There's a list context, but there always has to be something in the context, and this something is never a list. It might be a hash, it might be an array, or a sequence of comma operators. But keys doesn't want to see the hash (or array) in a list context, it wants to see its underlying HV or AV (which also makes getting the keys much faster, Perl doesn't really iterate over alternating keys and values, skipping the latter).

    map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]
      I understand that there's no list datatype - that perhaps it is used shorthand for something which can be evaluated in list context, but how can I reconcile this with the fact that subroutines return lists? Is it more correct to say that subroutines return a sequence of comma operators?
        I have to disagree with brother Choroba, Lists exist...

        ... but as temporary stack entries and not as allocated variables.

        So something like %h = @a (theoretically ) means:

        • push all array elements on a stack
        • read all stack elements into a hash
        (that's simplified, because optimization might kick in)

        There is also dedicated syntax for lists, like

        • () for empty list
        • (...)[n] for nth list element
        • , as list constructor (but only in list context)
        Update

        What you actually want is a list of pairs which doesn't exist in Perl, but in some other languages, like Raku afaik.

        Otherwise it's totally ambiguous to tell what keys LIST is supposed to mean, if LIST was a @array.

        Cheers Rolf
        (addicted to the Perl Programming Language :)
        Wikisyntax for the Monastery