Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transforming hash keys to an array

Tags:

arrays

hash

perl

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

like image 546
user238021 Avatar asked Nov 30 '22 03:11

user238021


2 Answers

why not do easier

my @array = ( keys %hash )
like image 183
Anatoliy Khmelevskiy Avatar answered Dec 06 '22 00:12

Anatoliy Khmelevskiy


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:
like image 44
TLP Avatar answered Dec 05 '22 22:12

TLP