7
use constant {
    COLUMNS => qw/ TEST1 TEST2 TEST3 /,
}

Can I store an array using the constant package in Perl?

Whenever I go on to try to use the array like my @attr = (COLUMNS);, it does not contain the values.

2
  • Use named constants, but don't use constant. Commented Aug 12, 2013 at 13:40
  • Even after modifying your code as shown by the answers below, the result will not be very useful as you can still modify the contents of a constant reference: perl -e 'use constant C => [1,2,3]; C->[1] = 5; print C->[1]. "\n";' Commented Sep 5, 2018 at 8:25

2 Answers 2

12

Or remove the curly braces as the docs show :-

  1 use strict;
  2 use constant COLUMNS => qw/ TEST1 TEST2 TEST3 /;
  3 
  4 my @attr = (COLUMNS);
  5 print @attr;

which gives :-

 % perl test.pl
TEST1TEST2TEST3

Your code actually defines two constants COLUMNS and TEST2 :-

use strict;
use constant { COLUMNS => qw/ TEST1 TEST2 TEST3 /, };

my @attr = (COLUMNS);
print @attr;
print TEST2

and gives :-

% perl test.pl
TEST1TEST3
Sign up to request clarification or add additional context in comments.

1 Comment

+1 The use of braces (a hashref) imposes an interpretation the OP doesn't want.
9

Use a + to signify that it's a contant.

use constant {
  COLUMNS => [qw/ TEST1 TEST2 TEST3 /],
};

print @{+COLUMNS};

The + is a hint to the interpreter that the constant is actually a constant, and not a bare word. See this reply for more details.

1 Comment

It is a hint to interpreter, to make disambiguation. Check stackoverflow.com/a/21173602/223226

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.