daveg
daveg

Reputation: 1201

How can I operate on a list which is identified by a string?

I would like to be able to operate on a list in Perl which is identified by a string. Code can describe this better...

my @colors = ("red", "white", "blue");
my @flavors = ("vanilla", "mint", "chocolate");

print "What favorites do you want to see ?";
my $fav_list = <>;  chomp($fav_list);

foreach my $favorite (???) {
    print "$favorite\n";
}

Given that $fav_list is either "colors" or "flavors", what should/could "???" in the code above be in order to print out the correct list?

Upvotes: 3

Views: 94

Answers (3)

Polar Bear
Polar Bear

Reputation: 6798

Slightly different approach to the problem

use strict;
use warnings;
use feature 'say';

my($answer, $choice);

my @colors  = qw/red white blue/;
my @flavors = qw/vanilla mint chocolate/;

print "What favorites do you want to see? ";

$answer = <>;
chomp($answer);

$choice = [];
$choice = \@colors  if $answer eq 'colors';
$choice = \@flavors if $answer eq 'flavors';

say for @{ $choice };

Upvotes: 0

Miguel Prz
Miguel Prz

Reputation: 13792

After you get the $fav_list, do this:

my @selected_list = (); 
if( $fav_list eq "colors" ) {
    @selected_list = @colors;
}
elsif( $fav_list eq "flavors" ) {
    @selected_list = @flavors;
}

for my $favorite ( @selected_list ) {
    print "$favorite\n";
}

Upvotes: 0

simbabque
simbabque

Reputation: 54323

I assume you want to print the elements of @colors if the input is "colors". The right way to do this is to use a hash, and store array references behind its keys.

Do not use user input as variable names.

my @colors = ("red", "white", "blue");
my @flavors = ("vanilla", "mint", "chocolate");

my %favorites = (
    colors  => \@colors,
    flavors => \@flavors,
);

print "What favorites do you want to see ?";
my $fav_list = <>;  chomp($fav_list);

foreach my $favorite ( @{ $favorites{$fav_list} } ) {
    print "$favorite\n";
}

The backslash \ takes a reference to the array. That's how you build a multi-dimensional data structure in Perl. Hashes are the key/value pair (also called dict, dictionary or object in other languages) type data structure.

Note that it makes sense to check if the key exists first. Also see perlref. and perlreftut.

Upvotes: 7

Related Questions