Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl constant array

Tags:

perl

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.

like image 638
Takkun Avatar asked Aug 12 '13 13:08

Takkun


People also ask

Can an array be a constant?

Arrays are Not Constants Because of this, we can still change the elements of a constant array.

How do I declare a constant in Perl?

Use $hash{CONSTANT()} or $hash{+CONSTANT} to prevent the bareword quoting mechanism from kicking in. Similarly, since the => operator quotes a bareword immediately to its left, you have to say CONSTANT() => 'value' (or simply use a comma in place of the big arrow) instead of CONSTANT => 'value' .

How do I initialize an array in Perl?

Since perl doesn't require you to declare or initialize variables, you can either jump right in and call push , or you can first create an empty list (by assigning the value () to the list), and then start using push .


1 Answers

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
like image 71
Himanshu Avatar answered Nov 07 '22 06:11

Himanshu