简体   繁体   中英

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;
}

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";
}

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM