简体   繁体   中英

Always treat hash element as array?

If I have a hash of data from a JSON import, is there a neat way to handle cases where an element could be either a value or an array of values?

So it could be

'blah' => [1,2,3,4,5]

or

'blah' => 1

Can I 'force' blah to be an array, even if it's not, so I can iterate over it and not worry about the number of elements?

I thought I could possibly push the contents of blah onto an empty array which would either push the single value onto the array or join the two arrays together. Is there a neat/best way to do this?

Assuming it will always be either a scalar number or an array reference:

Test, explicitly, if it is a reference. If it is, then assign it back to itself. Otherwise, wrap it in an array reference and assign that instead.

$foo{blah} = (ref $foo{blah}) ? $foo{blah} : [ $foo{blah} ];

It is not clear what you try to achieve, more details with sample code demonstrating the usage would be more helpful

use strict;
use warnings;

use Data::Dumper;

my $debug = 0;

my %hash = ( 'a' => 1, 
             'b' => [2,3,4,5,6,7,8,9], 
             'c' => { 'x' => 'one', 'y' => 'two', 'z' => 'three' }
            );

print Dumper(\%hash) if $debug;

while( my ($k,$v) = each %hash ){
     print "[variable] $k = $v\n"        if ref $v eq '';
     print "[array   ] $k\n", Dumper($v) if ref $v eq 'ARRAY';
     print "[hash    ] $k\n", Dumper($v) if ref $v eq 'HASH';
}

Please visit following webpage , I believe you will find it useful

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