Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Re: Flag variables

by webfiend (Vicar)
on Mar 03, 2003 at 21:04 UTC ( #240158=note: print w/ replies, xml ) Need Help??


in reply to Flag variables

Flags are often the easiest way to say something when you have a small programming vocabulary. In my early Perl code, I used flags all over the place. Now I hardly ever use them, preferring instead to find better ways to ask the question "Is this true?" - at least throwing the messiness off into a subroutine.

Now, there's nothing wrong with using flag values. They provide a convenient means of saying "do this if that is true". If they are properly named, it's even better: $flag could also be named as $has_foo. Keep your definition of the flag close to where you actually use it, too. That's why I often put flag-reliant code into its own subroutine:

sub has_phrase { my ($phrase, @wordlist) = @_; my $is_true = 0; foreach my $var (@wordlist) { if ($var eq $phrase) { $is_true = 1; last; } } return $is_true; } # ... called later if (has_phrase("foo", @somearray)) { &someaction }

As you learn more about syntax and how to express yourself, though, you find these flags getting in the way. Here is a much quicker way to write the same subroutine:

sub has_phrase { my ($phrase, @wordlist) = @_; foreach my $var (@wordlist) { return 1 if ($var eq $phrase); } return; }

It could be made even more concise, but this is the limit of my verbose programming style. You get the idea, though. Flags are fine, but they usually represent something you still have to learn about the language.

And that's not even counting the complete mess you can end up with when you have too many flags. I abandoned one of my early projects eventually, just because it filled up with flags and special circumstances. It ended up getting too hard to read, and not important enough to refactor.


I just realized that I was using the same sig for nearly three years.


Comment on Re: Flag variables
Select or Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (4)
As of 2014-12-27 13:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (177 votes), past polls