Transforming hash keys to an array

18,743

Solution 1

Looks like a good time to use the non-destructive /r option for substitutions.

my @array = map s/^test(\d+)/part${1}_0/r, keys %a;

For perl versions that do not support /r:

my @array = map { s/^test(\d+)/part${1}_0/; $_ } keys %a:

Solution 2

why not do easier

my @array = ( keys %hash )

Solution 3

my @a;
for (keys %hash) {
   push @a, 'part' . ( /^test([0-9]+)/ )[0] . '_0';
}

But that just begs for map to be used.

my @a =
   map { 'part' . ( /^test([0-9]+)/ )[0] . '_0' }
    keys %hash;
Share:
18,743
user238021
Author by

user238021

Updated on June 20, 2022

Comments

  • user238021
    user238021 almost 2 years

    I have a hash(%hash) with the following values

    test0  something1
    test1  something
    test2  something
    

    I need to build an array from the keys with the following elements

    @test_array = part0_0 part1_0 part2_0
    

    Basically, I have to take testx (key) and replace it as partx_0

    Of course, I can easily create the array like the following

    my @test_array;
    
    foreach my $keys (keys %hash) {
        push(@test_array,$keys);
    }
    

    and I will get

    @test_array = test0 test1 test2
    

    but what I would like is to get part0_0 instead of test0, part1_0 instead of test1 and part2_0 instead of test2

  • ikegami
    ikegami over 12 years
    Note: Only available in 5.14+
  • TLP
    TLP over 12 years
    @ikegami Where do you look that up?
  • Zaid
    Zaid over 12 years
  • TLP
    TLP over 12 years
    @Zaid That's only good if you already know which version it came with, though... Like a phonebook that's sorted in numerical order. =P
  • Zaid
    Zaid over 12 years
    @TLP : I sense a question coming along ;) ... go ahead and ask it before I do :)
  • TLP
    TLP over 12 years
    @Zaid What, you want me to ask a Question-question? Nah, you go ahead.
  • Zaid
    Zaid over 12 years
    @TLP : Looks like it been asked before: stackoverflow.com/q/2500892/133939
  • TLP
    TLP over 12 years
    @Zaid Brian d foy and at least 5 others seem to think it's limited though.. I'm testing it now, but ppm doesn't seem to like downloading Perl::MinimumVersion.
  • Jacob
    Jacob over 12 years
    perl -MPerl::MinimumVersion -E'say Perl::MinimumVersion->new(\"s///r")->minimum_version' prints 5.004. Obviously it hasn't been updated to know about /r yet.
  • Ricky Levi
    Ricky Levi almost 8 years
    in some versions of Perl you'll receive a scalar ( saying how many keys you have )
  • Chris
    Chris about 4 years
    is this an older or newer feature? That is, in "current" versions of Perl, which way does it work?