in reply to Mapping array over a hash

For a quick, but possibly wrong solution, you could use a hash slice:

my %newhash; @newhash{@array} = @oldhash{@array};

A pitfall here is that if there's a value in the array that doesn't correspond to a key in the original hash, you'll autovivify an entry.

If you don't have such control over your data, try:

my %new = map { $_=> $old{$_} } grep { defined $old{$_} } @array;

The grep gets all the entries in the hash that (a) have a key corresponding to an entry in the array and (b) have defined values. The map turns that list into a hash.

Change that defined to exists if you don't mind getting back keys associated with undefined values.

HTH!

perl -e 'print "How sweet does a rose smell? "; chomp ($n = <STDIN>); +$rose = "smells sweet to degree $n"; *other_name = *rose; print "$oth +er_name\n"'

Replies are listed 'Best First'.
Re: Re: Mapping array over a hash
by japhy (Canon) on Jul 20, 2001 at 18:38 UTC
    Autovivification does not occur here; it only happens when the non-existent thing in question is an lvalue:
    %hash = qw( a 1 b 2 c 3 ); @array = (1,2,4,8); $x = $hash{z}; # no auto-viv $x = $array[10]; # no auto-viv 1 for $hash{y}; # auto-viv 1 for $array[7]; # auto-viv
    Bonus: why are those bottom two treating the value in question as an lvalue?

    _____________________________________________________
    Jeff japhy Pinyan: Perl, regex, and perl hacker.
    s++=END;++y(;-P)}y js++=;shajsj<++y(p-q)}?print:??;

      looks like because they're being evaluated in list context - but I don't even know what vivification is, let alone autovivification

      I'm off to look it up.

      update: hell, I can't even spell it!

      update2: found a useful article here - turns out I do most of this already - I just didn't know what it was called!

      update3: for supersearch: "what is autovivification?" and for muppets like me in the supersearch "what is autovivication?"

      "Argument is futile - you will be ignorralated!"

        I was criticizing the use of the term "auto-vivify" -- merely creating entries in a hash by assigning values to them is not auto-vivifying. The process of these entries coming into being because their existence was implied is autovivification.

        _____________________________________________________
        Jeff japhy Pinyan: Perl, regex, and perl hacker.
        s++=END;++y(;-P)}y js++=;shajsj<++y(p-q)}?print:??;