Subject: | wish: arrayify |
Here's a pattern I see frequently in my own code that I think deserves a
utility function:
I have a scalar that either holds a single value or an array reference
that holds multiple values. I want to always be table to treat the
thing as an an array in either use.
Use cases:
CGI.pm's param() method returns either a single value or multiple
values. Once translated into a hash, you have this kind of data structure.
Throughout the Data::FormValidator interface, you can give simple scalar
values for simple cases, or an arrayref of values for more complex cases.
A function for this is implemented internally in Data::FormValidator,
and has worked well over the years. Here it is:
# takes string or array ref as input
# returns array
sub arrayify {
# if the input is undefined, return an empty list
my $val = shift;
defined $val or return ();
if ( ref $val eq 'ARRAY' ) {
# if it's a reference, return an array unless it points an empty
array. -mls
return (defined $val->[0]) ? @$val : ();
}
else {
# if it's a string, return an array unless the string is missing
or empty. -mls
return (length $val) ? ($val) : ();
}
}