in reply to Re^3: Why is my script not printing anything?and how to add a switch case in perl
in thread Why is my script not printing anything?and how to add a switch case in perl

I am using perl 5.6.1 ,would using "use feature qw(switch say);" work

  • Comment on Re^4: Why is my script not printing anything?and how to add a switch case in perl

Replies are listed 'Best First'.
Re^5: Why is my script not printing anything?and how to add a switch case in perl
by GrandFather (Saint) on Dec 02, 2010 at 06:03 UTC

    No! Those features require Perl 5.10 or later. For earlier versions of Perl you should use a cascade of if/elsif statements.

    True laziness is hard work

      Can i use something like below?

      if($answer) error_entry(); else warning_entry();
        No, you need the braces, and each time you don't indent a kitten dies:
        if ($answer) { error_entry(); } else { warning_entry(); }

        That is about half way between C and Perl. Even if you add the missing pairs of {} to turn that into Perl, it's still not really what you want probably. The equivalent of the code I gave above would be more like:

        if ($answer eq '1') { error_entry (); } elsif ($answer eq '2') { warning_entry (); } else { die "Expected 1 or 2 for the answer. Got $answer\n"; }

        It bothers me that correct basic syntax doesn't flow off your finger tips. Is this because you are new to Perl and are recycling code from other places, or are more familiar with a different language and are just coming up to speed with Perl or is there some other reason? We may be able to recommend tutorial material or suitable books if any of these cases apply.

        True laziness is hard work
Re^5: Why is my script not printing anything?and how to add a switch case in perl
by pemungkah (Priest) on Dec 02, 2010 at 23:42 UTC
    Use a dispatch table instead:
    my %actions = ( 1 => \&error_entry, 2 => \&warning_entry, ); my $action_sub = $actions{$value_to_check} || \&default_action; $action_sub->($args_for_this);
    Your individual actions need to have matching call signatures (same number of arguments, same order) for this to work. If your subs already exist and don't have exactly the same signatures, you can either write wrapper subs or use anonymous subs in the actions table. Note that if you want to call methods, you'd simply put the method names in the action table and then use this to call the selected method:
    $object->$method($args_for_this);
    This makes it totally trivial to add or change the number of alternatives, and is a hash lookup, so no matter how many alternatives you have, the time to find and run any given one is exactly the same (handwaving hash collisions here).