2

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 .

1 Answer 1

2

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.
}
Sign up to request clarification or add additional context in comments.

4 Comments

i think its hardest section of programming , Thanks DVK
@user1212132 - not sure what you mean by hardest section. Also, on StackOverflow, it's considered a good form to accept (by clicking on a check mark next to the answer) an answer if it was helpful as a form of thanks :)
do u know what is the reason of this error : Not enough arguments for index at line 10 near "index]"
DVK forgot the $ and rather than calling the $index variable, invoked the index function, which isn't what he meant. Fixed now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.