Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

perl can't use string as an array ref

I have 4 apps. let's call them: App1, App2, App3 and App4.

for each of these apps I have an array: for example:

my @App1_links = (...some data...);
my @App2_links = (...some data...);
my @App3_links = (...some data...);
my @App4_links = (...some data...);

Now I have a loop in my code that goes thru these 4 apps and I intend to do something like this:

my $link_name = $app_name . "_links";
    where $app_name will be App1, App2 etc...

and then use it as : @$link_name

Now this code does what I intend to do when I don't use: use strict but not otherwise

The error is: Can't use string ("App1_links") as an ARRAY ref while "strict refs" in use at code.pm line 123.

How can I achieve this functionality using use strict.

Please help.

like image 504
soothsayer Avatar asked Dec 09 '25 20:12

soothsayer


2 Answers

You are using $link_name as a symbolic reference which is not allowed under use strict 'refs'.
Try using a hash instead, e.g.

my %map = (
    App1 => \@App1_links,
    ...
);
my $link_name = $map{$app_name};
like image 156
Eugene Yarmash Avatar answered Dec 12 '25 16:12

Eugene Yarmash


As I say elsewhere, when you find yourself adding an integer suffix to variable names, think "I should have used an array".

my @AppLinks = (
    \@App1_links,
    \@App2_links,
    \@App3_links,
    # ...
);

for my $app ( @AppLinks ) {
    for my $link ( @$app ) {
        # loop over links for each app
    }
}

or

for my $i ( 0 .. $#AppLinks ) {
    printf "App%d_links\n", $i + 1;
    for my $link ( @{ $AppLinks[$i] } ) {
        # loop over links for each app
    }
}
like image 41
Sinan Ünür Avatar answered Dec 12 '25 15:12

Sinan Ünür



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!