Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an Array Ref in one line in Perl

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?

like image 790
Kirs Kringle Avatar asked May 03 '18 12:05

Kirs Kringle


2 Answers

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'
        ];
like image 59
Zzyzx Avatar answered Nov 11 '22 12:11

Zzyzx


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.

like image 42
Glenn Avatar answered Nov 11 '22 12:11

Glenn