T
Tore Aursand
Hi!
One thing that happens quite often when I program in Perl, is that I need
to initialise a variable to be an array reference.
Let me explain what I'm talking about:
sub init {
my %ARGS = @_;
my $paths = $ARGS{'paths'} || [];
}
In the code above, I want $self->{'_paths'} to always be an array
reference, even if $ARGS{'paths'} is just a plain string. How can I do
this the best way?
Currently, I'm stuck with code like this:
my $paths = $ARGS{'paths'} || [];
$paths = ( ref($paths) eq 'ARRAY' ) ? $paths : [ $paths ];
It seems to work, though, but I feel that there's something wrong with
this approach...?
Even though I have a lot og scripts and modules which uses this code, I
have luckily gathered the code above in my Misc module (50K and still
growing). The function is called 'as_arrayref' and is quite nice;
my $ref = as_arrayref( $something );
Tata!
One thing that happens quite often when I program in Perl, is that I need
to initialise a variable to be an array reference.
Let me explain what I'm talking about:
sub init {
my %ARGS = @_;
my $paths = $ARGS{'paths'} || [];
}
In the code above, I want $self->{'_paths'} to always be an array
reference, even if $ARGS{'paths'} is just a plain string. How can I do
this the best way?
Currently, I'm stuck with code like this:
my $paths = $ARGS{'paths'} || [];
$paths = ( ref($paths) eq 'ARRAY' ) ? $paths : [ $paths ];
It seems to work, though, but I feel that there's something wrong with
this approach...?
Even though I have a lot og scripts and modules which uses this code, I
have luckily gathered the code above in my Misc module (50K and still
growing). The function is called 'as_arrayref' and is quite nice;
my $ref = as_arrayref( $something );
Tata!