user1212132
user1212132

Reputation: 23

Do unique work for each element of Array

I create a txt file that have 3 element and i wrote this code :

my $in_file1 = 'file.txt';
open DAG,$in_file1;
my @shell=<DAG>;
close DAG;
chomp(@shell);
foreach my $shell(@shell){
 # and etc code 

and i want if the number of element is 0 do something and if 1 do other thing and if 2 ... . for example

if (@shell[0]) print "hi"; if(@shell[1]) print "bye" if(@... 

what am i going to do ? what is the best and simplest way for doing this ? Thanks .

Upvotes: 2

Views: 135

Answers (1)

DVK
DVK

Reputation: 129403

One of the best ways to do work based on a value is a hash/redirect table, especially if you need to do that sort of work more than once in a program. This involves creating a hash whose keys are the selector values, and values are references to subroutine doing work.

In your case, you are doing based on # of words, so a lookup array is a good way to go:

sub bye { print "bye"; }
my @actions = (
    sub {  },            # do nothing for 0. Using anonymous sub
    sub { print "hi" },  # print "hi" for 1
    \&bye,               # for 2 - illustrate how to use reference to existing sub
);
use File::Slurp; # To read the file
my @lines = read_file("my_file");
for (my $index = 0; $index < @lines; $index++) {
     &{ $actions[$index] }($lines[$index]); 
     # Call the sub stored in an array in correct place
     # Pass it the line value as argument if needed.
}

Upvotes: 2

Related Questions