Michael Kavanagh wrote:
>
> Hi there,
Hello,
> I've got a hash that has keys which contain either
> - array references
> - scalar values
>
> for example:
> @values = (12398712984, 19286192879);
> $hashofarrays{'family'}{'arrayref'} = \@values;
> $hashofarrays{'family'}{'scalar'} = 12938712938;
It would be simpler if you stored all the values as arrays instead of
scalars.
$hashofarrays{'family'}{'arrayref'} = [ 12398712984, 19286192879 ];
$hashofarrays{'family'}{'scalar'} = [ 12938712938 ];
> I'm trying to map the hash into another array that would just be a flattened
> list of values. (a combination of the scalar values and the individual array
> values)
>
> I'm iterating through each key in the hash and then using 'map' on the key
> to do this at the moment.
>
> I can get it to work for all the array references by mapping on the
> de-referenced array ref, like this:
> map { push @items, $_ } ( @{$hashofarrays{'family'}{'arrayref'} } );
If you have map in a void context you should be using for instead.
> But that ignores all the scalar values...it only gets the keys that contain
> array references.
>
> To get the scalars, the following works:
> map { push @items, $_ } ( $hashofarrays{'family'}{'scalar'} );
>
> Is there an elegant / idiomatic way to do both at once?
> I'm guess I could do it using a conditional that checks the hash value and
> executes one of the above statements as I iterate through the hash keys, but
> if theres a better way...
To create the array:
my @items = map { ref ? @{$hashofarrays{'family'}{$_}} :
$hashofarrays{'family'}{$_}
} keys %{$hashofarrays{'family'}};
To add to an existing array:
push @items, map { ref ? @{$hashofarrays{'family'}{$_}} :
$hashofarrays{'family'}{$_}
} keys %{$hashofarrays{'family'}};
Or using for:
push @items, ref ? @{$hashofarrays{'family'}{$_}} :
$hashofarrays{'family'}{$_}
for keys %{$hashofarrays{'family'}};
These assume that the value is either an array reference or a scalar.
John
--
use Perl;
program
fulfillment
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]