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

I have an array of numbers, and an empty hash:
my @array = (1..10); my %hash = ();
I remember a one liner, that would populate the keys of the hash with the elements of the array, but now it escapes me (age?). I seem to remember it was something like:
%hash{@array} = (1) x scalar(@array};
But that doesn't work. Any ideas?

Replies are listed 'Best First'.
Re: 1 line array to hash converter
by stefp (Vicar) on Sep 21, 2001 at 18:39 UTC
    $hash{$_}++ for @array;

    The value associated to a key is the number of elements in @array which have the value of the said key.

    The solution you searched for and explicited by suaveant gives 1 for each value even if the key appears many times in the array.

    TMTOWTDI.

    -- stefp

      Thanks everyone. I think stefp offered the most elegant solution, because: 1. Shortest amount of code. 2. Elegant and easy to read and understand. 3. Assigns something useful to the hash value. Of course, in hindsight, it was *obvious*.
Re: 1 line array to hash converter
by davorg (Chancellor) on Sep 21, 2001 at 18:48 UTC

    If you only need to populate the keys of the hash, then

    @hash{@array} = ();

    will work. The values will all be undef.

    --
    <http://www.dave.org.uk>

    "The first rule of Perl club is you don't talk about Perl club."

Re: 1 line array to hash converter
by suaveant (Parson) on Sep 21, 2001 at 18:37 UTC
    Almost!
    @hash{@array} = (1) x scalar(@array};
    need to put an @ at the front... not sure why, but you do

                    - Ant
                    - Some of my best work - Fish Dinner

      The @ sign pretty much tells the interpreter to expect a SLICE, and since hash is (hopefully) already defined as a hash, you get a hash slice. :)

      japhy has a great little 'tutorial' i found (via google) at http://www.crusoe.net/~jeffp/docs/using_refs

      jeffa

        Actually, it's the type of brackets - {} - that tells Perl that's it's a hash slice.

        --
        <http://www.dave.org.uk>

        "The first rule of Perl club is you don't talk about Perl club."

      Nit: useless use of scalar
      @hash{@array}=(1) x @array;
      Works peachy as well.
Re: 1 line array to hash converter
by thpfft (Chaplain) on Sep 21, 2001 at 18:44 UTC

    How about the less glamorous:

    my %hash = map { $_ => 1 } @array;

    which gets you off the separate declaration of %hash and is more versatile in the long run. Or to make your example a real oneliner:

    my %hash = map { $_ => 1 } (1..10);

    But i assume that in something real you'd be using an array that existed already.