http://www.perlmonks.org?node_id=240158


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.