norbdum
norbdum

Reputation: 2491

How to use a string in a variable as a Perl array reference

I am trying to run a loop on the strings in the $ACES_1_key but I get Can't use string ... as an ARRAY ref while "strict refs" in use.

my $ACES_1_key = ("`NIL-RETURN`,`ASSESSEE-NAME`,`LTU`,`MONTH`,`RETURN-YEAR`,`REGISTRATION-NUMBER`");

foreach my $key (@$ACES_1_key) {
  print $key;
}

Upvotes: 0

Views: 153

Answers (2)

Borodin
Borodin

Reputation: 126722

You should avoid using capital letters in lexical variable names. They are reserved for global identifiers such as package names.

If you are trying to set up an array reference in the first place then you want something like this:

my $aces_1_key = [ qw[ NIL-RETURN ASSESSEE-NAME LTU MONTH RETURN-YEAR REGISTRATION-NUMBER ] ];

foreach my $key (@$aces_1_key) {
  print $key, "\n";
}

output

NIL-RETURN
ASSESSEE-NAME
LTU
MONTH
RETURN-YEAR
REGISTRATION-NUMBER

Alternatively, if you have a string that you need to split into individual substrings then there are a few ways to. The program below shows one. It splits the string at the commas to produce a list of quoted substrings. Then the quotes are removed inside the loop using tr//. The output is identical to that of the previous example.

my $aces_1_key=("`NIL-RETURN`,`ASSESSEE-NAME`,`LTU`,`MONTH`,`RETURN-YEAR`,`REGISTRATION-NUMBER`");

foreach my $key (split /,/, $aces_1_key) {
  $key =~ tr/`//d;
  print $key, "\n";
}

Upvotes: 2

JB.
JB.

Reputation: 42094

Try this:

my @ACES_1_key = (
    'NIL-RETURN',
    'ASSESSEE-NAME',
    'LTU',
    'MONTH',
    'RETURN-YEAR',
    'REGISTRATION-NUMBER'
);
foreach my $key (@ACES_1_key) {
    print $key;
}

(I requoted the elements and made the variable an actual array)

(and didn't test it)

Upvotes: 1

Related Questions