in reply to Why is my script not printing anything?and how to add a switch case in perl

This is a lovely example of why global variables are a bad idea! By making all your variables global you almost completely obviate the primary reason for using strict. Don't use globals like that!

As toolic observed your rubbishy indenting hides the fact that you have nested your 'main' code inside one of your subroutines. A big comment in the code does nothing at all to fix that!

Keep variables local and pass them around to subroutines if required. Id' provide sample code to show how this could be tidied up, but there's not enough context for me to be sure just what you are parsing and how you really want to handle errors. If you provide more context (a small sample input file and expected output would help) someone might provide a nice example for you to work from.

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

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

    Is there a way I can attach files to my replies?I can attach sample input and output files?

    Enter your choice: 1.Errors 2.Warnings

    Would the following sample switch code work when the user is given the above choices?

    given($_) { when (/1/) { error_entry(); } when (/2/) { warning_entry(); } }

      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

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