Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Braces around a section of code

by thnksnw (Novice)
on Jun 26, 2019 at 13:16 UTC ( [id://11101936]=perlquestion: print w/replies, xml ) Need Help??

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

I have seen braces used around a section of code. What would be the pros/cons for doing this?

{ # ---- START POSE ---- if ($pose_name eq ''){ print "ERROR: \"start\" POSE - NOT FOUND" } for ($i=0; $i<$armload_cnt; $i++){ if ($armload_mass[$i] == 0){ print "ERROR: ARMLOAD $armload_num[$i] - MASS VALUE IS ZERO" } } }

Replies are listed 'Best First'.
Re: Braces around a section of code
by Athanasius (Archbishop) on Jun 26, 2019 at 13:30 UTC

    Hello thnksnw, and welcome to the Monastery!

    Braces create a block, which has its own lexical scope. So you might do something like this:

    { my $foo = 42; # do more with $foo here } # $foo is no longer in scope here

    to restrict the scope of $foo to only that part of the code where it ought to be used.

    In the code shown, I can’t see any advantage to the braces. Is this the real code? If so, maybe the author was intending to add an if above it to remove the code from execution or even from compilation. For example,

    use constant DEBUG => 0; ... if (DEBUG) { # This code will not be compiled }

    Hope that helps,

    Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

Re: Braces around a section of code
by Eily (Monsignor) on Jun 26, 2019 at 13:33 UTC

    There are many good reasons to do that, none of which apply here :P

    It could be to limit the scope of a variable, eg to make sure that a filehandle is closed and destroyed when you are done using it. But there's no variable limited to the scope of that block. And it looks like the variables used or not lexical (my) anyway, since the loop variable which should be limited to the loop is not.

    It could to separate the code logically, and make it easier to read. But here the indentation it very unhelpful so I doubt that this was a concern. Edit: the comment at the top might be to describe the whole block though?

    A single block also works like a loop that is executed once. So the keywords redo (which goes back to the start of the block), next and last (both of which jump to the end of the block) can be used. But this is not the case here.

    So my guess here would be that there used to be a condition or function which was removed, but not the corresponding block. Or some other unintentional reason.

    Edit: ++Discipulus for mentioning local as well. There's also lexically scoped pragmas (like autodie) whose effect only applies inside the current block. But there's no use statement here, so that's still not the reason.

Re: Braces around a section of code
by Discipulus (Canon) on Jun 26, 2019 at 13:34 UTC
    Hello thnksnw,

    using local with a variable is one of them

    my $var = 42; { local $var = 13; .. }

    This is particularly useful when dealing with $@ like explained in eval doc:

    { local $@; # protect existing $@ eval { ... };
    L*

    There are no rules, there are no thumbs..
    Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.
Re: Braces around a section of code
by hippo (Bishop) on Jun 26, 2019 at 14:01 UTC

    I agree with my fellow monks who have already replied and might simply add a reference to Coping with Scoping for good measure.

    For other clues as to why the author has used a block here, look at the immediately preceeding and following lines (which you have not yet shown us).

    Finally, this line:

    for ($i=0; $i<$armload_cnt; $i++){

    suggests that the author is either not the most familiar with Perl or perhaps has translated this code from another language and the outer braces might simply be a residual figment of that. The more Perlish way to write this loop would be

    for my $i (0 .. $armload_cnt - 1) {

    Edit: fixed off-by-one in perlish loop (thanks AnomalousMonk for spotting). This is another reason IMHO why Perlish loops are superior - there's no need to inspect the operators inside the brackets so closely.

Re: Braces around a section of code
by LanX (Saint) on Jun 26, 2019 at 14:58 UTC
    Scoping as already mentioned by others is the most important benefit.

    But your code doesn't seem to use any

    Other motivations may be indentation of the inner code or wanting to apply loop control commands.

    For details on the latter please see perlsyn#Basic-BLOCKs

    Cheers Rolf
    (addicted to the Perl Programming Language :)
    Wikisyntax for the Monastery FootballPerl is like chess, only without the dice

Re: Braces around a section of code
by thnksnw (Novice) on Jun 26, 2019 at 15:05 UTC

    I am currently in "Self-Teaching" mode using Perl. I have done programming in the past - Kornshell, GSL, CLI and a little c++ (all self taught). So I know am lacking a lot of the simple fundamentals of writing code.

    I understand now what the braces mean with restricting the scope. The code I provided was only a portion of the section within a much larger program.

    I will try the suggested "FOR" command format.

    for my $i (0 .. $armload_cnt - 1) {

    Thank you for all your feedback.
Re: Braces around a section of code
by kcott (Archbishop) on Jun 27, 2019 at 09:03 UTC

    G'day thnksnw,

    Welcome to the Monastery.

    Having just posted a solution with three such anonymous blocks, I thought I'd share as another example. While not trying to take anything away from the examples already posted by others in this thread, my example is a fully functional script which may provide a little more insight as you're new to Perl.

    I also use this method a lot when writing test scripts. Many individual tests within the one script can be very similar; using anonymous blocks means I don't have to continually think up new variable names, remember to reinitialise existing variables, or worry about accidentally redefining variables (e.g. my $var = ... used more than once in the same scope).

    Have fun learning Perl.

    — Ken

Re: Braces around a section of code
by haukex (Archbishop) on Jun 30, 2019 at 09:44 UTC

    As the others have already said, the blocks introduce a new scope, and there are quite a few things in Perl that are lexically scoped. Just to add some more to the list that haven't been mentioned yet: several pragmas, such as strict and warnings, are also lexically scoped, and there are a few (rare!) cases where one might want to temporarily disable parts of those pragmas for a very small block of code.

    By the way, I would recommend properly indenting the inner blocks as well. perltidy can help.

      The inner block *might* have been indented properly by perltidy, but when it was done using tabs, it gets lost in the the cut-n-paste.

      I am not starting a discussin about leading whitespace here. I personally do not care at all, as long as it looks correct in my editor, you can mix tabs and spaces for my care. I more care about consistency and correct indentation (which seldom happens according to my own rules :P).


      Enjoy, Have FUN! H.Merijn

        Ah, good point, you are correct there is a mix of tabs and spaces in the original. But the innermost print appears to not be indented enough, so my comment still stands ;-)

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others having an uproarious good time at the Monastery: (4)
As of 2024-04-23 23:36 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found