Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: at continue, last

by InfiniteSilence (Curate)
on Jun 06, 2014 at 14:25 UTC ( #1089034=note: print w/replies, xml ) Need Help??


in reply to at continue, last

To me the secret to DRY (which is Do not Repeat Yourself -- I had to look that up) is to convert functionality to functions, encapsulate it in objects as methods that only execute in certain states, or to utilize some core language feature to reduce the code.

From your desire, "I need to ensure that a variable is decremented regardless of how an if clause is exited.." it reads like you want the decrement operation to happen automatically when something else occurs -- a form of encapsulation -- like this:

use strict; my $g_var = 1_000; sub special_dec { my $choice = shift; if ($choice) { --$g_var; } } my $thing = 'dog'; if ( $thing eq 'cat') { my $cntr = 0; while (++$cntr < 11) { last if (special_dec(900==900)); } } elsif ($thing eq 'dog') { my $cntr = 0; while (++$cntr < 11) { last if (special_dec(900==900)); } } print $g_var; 1; # of course prints 999

Now you don't have to think about manually decrementing or handling $g_var, something else does that for you.

Refactoring your solution may mean that you really need to write special operations that allow you to iterate over lists and handle certain internal values without the user of that object having to consciously know about them. I think in Perl there is a desire to try and solve a great many problems using language constructs and coding techniques when oftentimes the more obvious solution is to just push certain actions into functions or object methods instead. If you are doing Perl golf then disregard this post but your question doesn't read like that.

Celebrate Intellectual Diversity

Replies are listed 'Best First'.
Re^2: at continue, last
by djerius (Beadle) on Jun 06, 2014 at 18:06 UTC
    Sure, something like Scope::Guard would do the trick as well, but these approaches can be a mighty big sledgehammer when you're trying to swat a misquito. Yes, they do work, but...

    I don't see anything wrong with using built in language constructs if they're not golf-like. I don't consider adding an extra block within the if clause to be golf-like, but I acknowledge that tastes do vary.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (4)
As of 2022-01-28 20:29 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    In 2022, my preferred method to securely store passwords is:












    Results (73 votes). Check out past polls.

    Notices?