This is a thing I often want to do in different situations. But I'll state the problem in the specific form in which it's just arisen.
I have an array of hashes, call it
@tabs. Each hash in
@tabs has several keys, including
Action and
Suppress.
Suppress has a default value of 0. Sometimes, however, I want to turn
Suppress on (i.e. set its value to 1) depending on the value of
Action.
In this example I want to turn it on if
Action has one of three possible values, namely
GetAll Make or
MakeOnly.
The obvious way to do this, and the one I usually end up with, is
for (@tabs) {
if (
$_->{Action} eq 'GetAll' or
$_->{Action} eq 'Make' or
$_->{Action} eq 'MakeOnly'
) {
$_->{Suppress} = 1;
}
}
An arguably more elegant way would be
for my $hash (@tabs) {
if (grep {$hash->{Action} eq $_} qw/
GetAll
Make
MakeOnly
/) {
$hash->{Suppress} = 1;
}
}
... but, maybe it's just me, I don't like to get
grep out on such a trivial pretext (pass me my twelve bore, there's a snail in the lettuce patch) - plus, it involves creating a new var. Then there's a regex
for (@tabs) {
if ($_->{Action} =~ /(^GetAll$)|(^Make$)|(MakeOnly$)/) {
$_->{Suppress} = 1;
}
}
... but that comes with an overhead.
Then there's using the logical "or",
for (@tabs) {
if ($_->{Action} eq 'GetAll' || 'Make' || 'MakeOnly') {
$_->{Suppress} = 1;
}
}
... which is perfect except that, as eagle-eyed monks will have spotted it DOESN'T WORK, because 'GetAll' always returns a true value so that
'GetAll' || 'Make' || 'MakeOnly' is the same as
'GetAll' .... duh.
As you can see, I've already spent too much time thinking about this. Can some kind monk put me out of my misery, either by telling me there is no simple one line way to do this without additional overhead, or by telling me what it is?
§
George Sherston
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.