简体   繁体   中英

Convert an array of hashes to array of scalar values in Perl

I have a reference to an array of hashes like this

[
    {
        'parameters'              => '',
        'default_init_for_config' => '1',
        'name'                    => 'CWG.BasicCmode.sim',
        'init'                    => 'config/CWG.BasicCmode.sim'
    },
    {
        'parameters'              => '',
        'default_init_for_config' => '0',
        'name'                    => 'CWG.BasicCmode.MFA.sim',
        'init'                    => 'config/CWG.BasicCmode.MFA.sim'
    },
    {
        'parameters'              => '',
        'default_init_for_config' => '0',
        'name'                    => 'NoInit',
        'init'                    => 'config/NoInit'
    },
    {
        'parameters'              => '',
        'default_init_for_config' => '0',
        'name'                    => '2Vsim.mcc',
        'init'                    => 'config/2Vsim.mcc'
    },
]

I want to extract the value of the key name alone and assign it to the same array.

I deleted all the other keys and got something like this:

[
    {
        'name' => 'CWG.BasicCmode.sim'
    },
    {
        'name' => 'CWG.BasicCmode.MFA.sim'
    },
    {
        'name' => 'NoInit'
    },
    {
        'name' => '2Vsim.mcc'
    },
    {
        'name' => 'FakeAFF_HA.sim'
    },
    {
        'name' => 'ISCSI.sim'
    },
    {
        'name' => 'CWG.ExtendedCmode.sim'
    },
    {
        'name' => 'CWG.BasicCmodeNonHA.sim'
    },
    {
        'name' => '2Vsim.FakeAFF.mcc'
    },
]

How to proceed now?

The output should be

[
    'CWG.Basicmode.sim',
    'CWG.BasicCmode.MFA.sim',
    'NoInit',
    ...
]

To convert an array of hashes to a plain array of scalar values to be constructed from the hashes from a given key, you can use map . For example, assuming each hash has a name key, we can put the values of all these keys in a new arrayref like this:

my $new_array_ref = [map { $_->{name} } @$array_ref];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM