0

I am using the below code. On the right of and is a grep without a numerical comparison. Does that make sense?

if ( scalar( grep { $_ eq $ServerTypeId } keys %ServerTypes ) > 0
    and grep { isRegionOK( $_, $DC ) == 1 } keys %$destinationSummary )
{
    ...
}
ikegami
  • 367,544
  • 15
  • 269
  • 518
Syam Kumar
  • 23
  • 6
  • Can you clarify the question? Perhaps a more complete example of what you've tried, what happens when you run it, and what you want to happen instead? – IMSoP Nov 29 '14 at 17:31
  • Never mind .. I got the answer. – Syam Kumar Nov 29 '14 at 17:32
  • It would be better if your defined 'first' and 'second' parts along with code you tried. If you have your own answer that's fine, but please provide it. – JonB Nov 29 '14 at 17:34
  • Note: your first condition could be simplified to just `exists $ServerTypes{$serverTypeID}` – Miller Nov 29 '14 at 17:51
  • See `List::Util::any` for a more efficient (short-circuiting) option. – Slade Nov 29 '14 at 23:05

1 Answers1

3

Perl, like C, doesn't have a boolean type. The language defines certain values as being false, and the rest are true. See How do I use boolean variables in Perl?, Truth and Falsehood.

In scalar context, grep returns a count of matches. 0 is false and all other numbers are true, so treating the result of grep as a boolean checks if there were any matches. So yes, grep can very well be used as the argument of and.


Let's do some cleanup.

You have the following:

scalar( grep { $_ eq $ServerTypeId } keys %ServerTypes ) > 0
and
grep { isRegionOK( $_, $DC ) == 1 } keys %$destinationSummary

Checking if a non-negative number is greater than zero is the same as checking if it's true or false.

scalar( grep { $_ eq $ServerTypeId } keys %ServerTypes )
and
grep { isRegionOK( $_, $DC ) == 1 } keys %$destinationSummary )

and (and > before that) evaluates its arguments in scalar context, so no need for scalar.

grep { $_ eq $ServerTypeId } keys %ServerTypes
and
grep { isRegionOK( $_, $DC ) == 1 } keys %$destinationSummary

isRegionOK region surely returns a boolean value.

grep { $_ eq $ServerTypeId } keys %ServerTypes
and
grep { isRegionOK( $_, $DC ) } keys %$destinationSummary

exists is far more efficient at checking for the existence of a hash element by key.

exists($ServerTypes{$ServerTypeId})
and
grep { isRegionOK( $_, $DC ) } keys %$destinationSummary
Community
  • 1
  • 1
ikegami
  • 367,544
  • 15
  • 269
  • 518