Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation

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.

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (5)
As of 2021-06-24 10:29 GMT
Find Nodes?
    Voting Booth?
    What does the "s" stand for in "perls"? (Whence perls)

    Results (125 votes). Check out past polls.