ImJustAFriend has asked for the wisdom of the Perl Monks concerning the following question:

Hello again, Monks. I have a question for the collective genius of this monastery. I have googled for it, but I think I'm not asking google the right question. Here goes:

In my code, I have a piece that evaluates to a numeric value, either 4 or 6. In my test code snippet below, I am simply assigning the value statically for testing purposes. I want to use the value of this scalar in the name of an array further down in my code, so I can avoid "if else" blocks. However, this isn't working. I have read sites where the general consensus is that dynamic variable names are a bad idea, but based on the code that went along with those posts, I am not sure they apply to my situation. On to my code snippet:

#!C:/Perl64/bin/perl.exe use strict; use warnings; use Control::CLI; my $cli; my $output; my $temp; my $junk; my $port; my $result; my @STATION_LIST_6 = qw/A B C D E F/; my @STATION_LIST_4 = qw/A B C D/; ... my $STATION_CNT = 4; my $FREEMEM; print "Configuring blah blah blah...\n"; print "\tChecking free memory on appropriate blades to ensure there is + enough for application execution...\n"; foreach my $stid (@STATION_LIST_$STATION_CNT) { <-- This line doesn't + work... $junk = $cli->print("echo STATION_\$stid; su -c \"ssh STATION_\$st +id free -g\""); $output = $cli->cmd("password"); $FREEMEM = $output =~ m/^.*?\w+:\s+\d+\s+\d+\s+(\d+)\s.*$/s if ( $FREEMEM >= 4 ) { print "\t\tSTATION_$stid reports sufficient free memory...\n"; } else { print "\t\tSTATION_$stid reports insufficient free memory ($FR +EEMEM)... Please investigate and start application again... Exiting p +rogram.\n"; exit; } }

If anyone has any thoughts they could share, I would appreciate it. I REALLY want to avoid "if else" here, and dynamically figure out the value of the array to use. Thanks in advance, as always!

Replies are listed 'Best First'.
Re: Using Scalar In Array Name?
by toolic (Bishop) on Jan 19, 2014 at 23:25 UTC
      True, but you really shouldn't use a variable as a variable name unless you're absolutely sure there isn't a better way. That way lies madness. Go with the hash-of-arrays idea instead.

      Update: D'oh, scooped by Jim.

Re: Using Scalar In Array Name?
by AnomalousMonk (Archbishop) on Jan 19, 2014 at 23:44 UTC

    A hash-of-arrays, e.g.:

    >perl -wMstrict -le "my %STATION_LIST = ( 6 => [ qw/A B C D E F/ ], 4 => [ qw/A B C D/ ], 99 => [ qw/foo bar baz/ ], ); ;; my $STATION_CNT = 99; ;; foreach my $stid (@{ $STATION_LIST{$STATION_CNT} }) { print qq{station '$stid'}; } " station 'foo' station 'bar' station 'baz'
Re: Using Scalar In Array Name?
by ImJustAFriend (Scribe) on Jan 20, 2014 at 15:37 UTC

    Well, hash of arrays worked perfectly. I am on a bit of a schedule to get this code turned out, but I will read the mentioned articles later on.

    Thanks as always, Monks!