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

Dear monks,

How do i copy the keys of a hash to an array. I need to know, what is an efficient way of doing it, i.e. without losing much of my memory and my resources.

Yeah, one way of doing it, is to construct a foreach loop for that particular hash and then push each key individually into an array. but is this an efficient way (that uses minimal resources), if not what are the other mean, through which i can accomplish this.

Replies are listed 'Best First'.
Re: Copy hash's key to an array
by moritz (Cardinal) on Oct 21, 2011 at 14:13 UTC
Re: Copy hash's key to an array
by toolic (Bishop) on Oct 21, 2011 at 14:14 UTC
    The Perl built-in keys function does this:
    my @keys = keys %hash;
    Perl comes with documentation which can be queried from the command line:
    perldoc -q keys
Re: Copy hash's key to an array
by roboticus (Chancellor) on Oct 21, 2011 at 14:14 UTC

    sranrsm:

    What's wrong with:

    my @array_of_keys = keys %my_hash;

    ...roboticus

    When your only tool is a hammer, all problems look like your thumb.

Re: Copy hash's key to an array
by zwon (Abbot) on Oct 21, 2011 at 14:17 UTC

    Maybe I don't understand, but do you mean these:

    # copy keys to array @array = keys %hash; # copy values to array @array = values %hash; # copy key-value pairs to array @array = %hash

      Deak Monks,

      Thank you very much every one. But is there any other efficient way besides keys and pushing individual keys. I am just being here a bit curious because itz perl and here there's always another way.

        I'm sure there are other ways. You could treat the hash as an array, for instance, and use a loop to pull out all values with even-numbered indexes, starting with zero. But I doubt any other way could be as efficient as the built-in 'keys' function.

        I'm sure Perlmonks could find a few million silly ways to extract the keys from a hash without using the four character buildin called keys.

        But what's the point?