I was pondering on the question of whether I could make an array ref in one line in Perl. Sort of like you would define an array. I would normally do the following:
#!/usr/bin/perl
# your code goes here
use warnings;
use strict;
use Data::Dumper;
my @array = qw(test if this works);
my $arrayref = \@array;
print Dumper($arrayref);
My thought was you should be able to just do:
my $arrayref = \(qw(test if this works);
This, however, does not work the way I expected. Is this even possible?
You can do that by using the 'square-bracketed anonymous array constructor' for it. It will create an array reference 'literal'
my $arrayref = [ qw(test if this works) ];
or list every member out:
my $arrayref = [ 'test', 'if', 'this', 'works' ];
You could verify both results with Data Dumper:
$VAR1 = [
'test',
'if',
'this',
'works'
];
If your goal is to create an array reference in one line, use square brackets to create an array reference, which creates an anonymous array.
use Data::Dumper;
my $arrayRef = [qw(test if this works)];
print Dumper($arrayRef);
So if this is what you are looking to do, it is possible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With