Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Code Blocks

by Ronnie (Scribe)
on Jul 27, 2006 at 11:15 UTC ( [id://564022]=perlquestion: print w/replies, xml ) Need Help??

Ronnie has asked for the wisdom of the Perl Monks concerning the following question:

Hello Brothers, I'll preface this question with the honest observation that I think this is a dumb question and I'm embarassed that I've not found a solution but.......I haven't! Is there any way to have a block of code actioned on the right hand side of an or statement? I'm writing a series of subroutines that this is required for and using curly or normal brackets generates compilation errors! If any of these subroutines encounter an error a logfile needs to be updated (using an existing subroutine) and then the return should be actioned (I'm additionally sending the failure message to a generic job logfile - belt AND braces 4 me!). I thought that enclosing this code in a curly brackets block would suffice but alas no. The following is a wee noddy example of what I'm trying to get to work -
#!/usr/bin/perl -w # use strict ; # sub toytown { my $file = 'xxrcblocktest.pl' ; my $msg = "Unable to open File $file :: $!\n" ; open INF, "<$file" or print "\n\tmy message\n" ; print "\n\tActual error :: $!\n" ; return 0 ; print "\n\tU shouldn't c this msg!!!!!!!\n" ; return 1 ; } # my $script = "xxrcblocktest" ; # print "\n\t\t<***** Script $script S T A R T S\n" ; &toytown or die "\n\tError :: $!\n" ; print "\n\t\t<***** Script $script E N D S\n" ;

With this code if the file doesn't exist the outcome is
my message Error :: No such file or directory

If the file does exist I get
<***** Script xxrcblocktest S T A R T S Error ::
Am i just asking a dumb question that you can instantly answer or can't this be done? Thanks in anticipation,
Ronnie

Replies are listed 'Best First'.
Re: Code Blocks
by davorg (Chancellor) on Jul 27, 2006 at 11:17 UTC

    Sounds like you're looking for do.

    --
    <http://dave.org.uk>

    "The first rule of Perl club is you do not talk about Perl club."
    -- Chip Salzenberg

Re: Code Blocks
by GrandFather (Saint) on Jul 27, 2006 at 11:28 UTC

    Looks like you are bending over backwards to write obscure code. In fact it is so obscure that it's not even clear what you are trying to achieve. What is the desired result if the file exists?

    I suspect your code would be easier to understand and maintain if you use a simple if rather than try to be clever with logic operators.


    DWIM is Perl's answer to Gödel
      Sorry but I assumed from the sub name - toytown - that you'd work out that it's not production code just a small example of what I was trying to do. Thanks for the help, I've found 2 working options from the responses that I've had. Cheers, Ronnie

        Posting a short clear represntative sample is to be appluded (or up voted anyway). Posting something untidy and obscure that can not be easily run and doesn't seem to illustrate the issue at hand will not get you the best posible help (the down votes are incedental in that case).

        Although it's not clear from your original post, it may be that you were trying to execute several statements when something failed. There are ways to do that as others have mentioned (perhaps omitting the comma operator - see below). But much better is to use an if/else.

        Using an if makes it clear that a test is being made and what gets executed as a result of the test. It is easy to add stuff to be executed for the fail or success case without a lot of mental exercise. The code is easier to understand and easier to maintain.

        Oh, and the comma operator? I don't recommend it but:

        use warnings; use strict ; 0 or (print 'this'), (print " and that\n");

        DWIM is Perl's answer to Gödel
Re: Code Blocks
by wfsp (Abbot) on Jul 27, 2006 at 11:38 UTC
    My tuppence worth.

    An else is a bit like a code block on the righthand side of an or.

    if (open my $fh, '<', $file){ print "file opened\n"; else{ print "open failed: $!"; }
Re: Code Blocks
by Ieronim (Friar) on Jul 27, 2006 at 11:30 UTC
    I'll explain it by two examples:
    You want:
    open INF, "<$file" or print "\n\tmy message\n" ; "\n\tActual error :: $!\n" ; return 0 ;
    You can do:
    open INF, "<$file" or do{ print "\n\tmy message\n", "\n\tActual error :: $!\n" ; return 0 ; }
    OR:
    open INF, "<$file" or (print("\n\tmy message\n", "\n\tActual error : +: $!\n"), return 0)
    It will do what you want, if i understood the idea of your dirty, ugly code correctly.

         s;;Just-me-not-h-Ni-m-P-Ni-lm-I-ar-O-Ni;;tr?IerONim-?HAcker ?d;print
      Thanks for the help - "do" does the job I was looking for. My dirty ugly code was just knocked up to give a flavour of what I was trying to do - and I had missed a print verb before the "actual error" line - it's not real production code. The comma after the first print should be a semi-colon and there should be a semi-colon after the closing curly bracket, my missing a print verb before the Actual error string probably led to this omission and my confusion! Thanks for the help though I am wondering exactly, typo apart, what is dirty and ugly about it?
      Many thanks
      Ronnie
        typo apart, what is dirty and ugly about it
        IMHO:
        • The comment signs on empty lines are ugly
        • The spaces before semicolons are ugly
        • 2-column indent is ugly
        • Calling subs as &sub is ugly and often simply wrong
        And even,
        open ... or do { #blah blah blah };
        is more ugly than
        unless (open...) { #blah blah blah }
        Perl syntax is very flexible. It even allows to write the whole your program in one long line. But i recommend you to follow the more common coding standarts :) They are described, e.g. in perlstyle.

             s;;Just-me-not-h-Ni-m-P-Ni-lm-I-ar-O-Ni;;tr?IerONim-?HAcker ?d;print

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://564022]
Approved by GrandFather
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (4)
As of 2024-03-29 00:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found