7

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?

Kirs Kringle
  • 849
  • 2
  • 11
  • 26
  • See [my comments from today on this question](https://stackoverflow.com/q/50145350/1331451) for an explanation of why `\qw/foo bar/` doesn't work. – simbabque May 03 '18 at 12:39
  • 1
    `my $arrayref = \(qw(test if this works);` will give you a scalar reference to the last element in the list. `\"works"` – simbabque May 03 '18 at 12:43
  • @simbabque I read your answer and the perlreftut and it made sense and I came up with what people said here. Thank you. – Kirs Kringle May 03 '18 at 12:52

2 Answers2

17

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'
        ];
Zzyzx
  • 501
  • 3
  • 7
  • I was just reading the document @simbabque told me to read http://perldoc.perl.org/perlreftut.html and it hit me. Come back to post my own answer and you beat me to it. – Kirs Kringle May 03 '18 at 12:52
  • That is an array reference, but it is not a reference to the array variable `@array` in the question. There is a distinct difference! – simbabque May 03 '18 at 12:55
  • @simbabque - I suppose in that sense my example was not clearly showing what I wanted to accomplish. I wanted to do the above. I do understand that array does not exist in this scenario and now we just have an array REF that can be passed into different variables and will contain those values. My objective was to get rid of array as it seemed redundant. – Kirs Kringle May 03 '18 at 12:59
  • @KirsKringle in that case, yes, this is exactly what you needed. :) – simbabque May 03 '18 at 13:00
2

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.

Glenn
  • 1,169
  • 1
  • 14
  • 23