3

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.

Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378
soothsayer
  • 333
  • 2
  • 6
  • 14
  • It would be nice, if you provided more meaningful snippet. Do you have arrays with these names and are trying to access them? – user4035 Jul 19 '12 at 18:38
  • I thought I gave enough information. Please tell me what is ambiguous in the post and I can fix it. The names can be anything but the idea is what I want to express and get the point across to you. – soothsayer Jul 19 '12 at 18:48

2 Answers2

4

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};
Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378
4

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
    }
}
Community
  • 1
  • 1
Sinan Ünür
  • 116,958
  • 15
  • 196
  • 339
  • My loop is going through the 4 apps, hence my need to concatenate and get the link_name. I would have to change a lot of code to loop through the array. Any other ideas? – soothsayer Jul 19 '12 at 18:51
  • I do not see any valid reason to use `no strict 'refs';` here. Doing that would "solve" your problem for some value of "solve". The code above loops over all the links for all the apps. – Sinan Ünür Jul 19 '12 at 18:54