in reply to Re^2: 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

You can't attach files, but you can include the contents of text files in your reply by putting the text in code tags. Please though keep the size of such samples small - just enough to demonstrate the issue. Often that will mean creating suitable sample data (perhaps by trimming down a real file).

I'd write that as:

given($answer) { when ('1') {error_entry();} when ('2') {warning_entry();} default {die "Expected 1 or 2 for the answer. Got $answer\n";} }

Using a regex match would match on any answer containing a 1 digit for the first case and any answer containing a 2 digit for the second case. Maybe not a problem for your application, but as a general thing you should validate data and handle unexpected data in some appropriate fashion. die is most appropriate for production code when you are using it to throw exceptions that are caught by eval. Generally it is much better to die and have it handled (or not in which case to script does die) than to carry on processing bogus data.

True laziness is hard work
  • Comment on Re^3: Why is my script not printing anything?and how to add a switch case in perl
  • Download Code

Replies are listed 'Best First'.
Re^4: Why is my script not printing anything?and how to add a switch case in perl
by iphone (Beadle) on Dec 02, 2010 at 05:09 UTC

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

      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();
      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).