11

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?

3
  • See my comments from today on this question for an explanation of why \qw/foo bar/ doesn't work. Commented May 3, 2018 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" Commented May 3, 2018 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. Commented May 3, 2018 at 12:52

2 Answers 2

20

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'
        ];
Sign up to request clarification or add additional context in comments.

4 Comments

I was just reading the document @simbabque told me to read perldoc.perl.org/perlreftut.html and it hit me. Come back to post my own answer and you beat me to it.
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 - 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.
@KirsKringle in that case, yes, this is exactly what you needed. :)
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.