Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister

Re: If conditional checks

by Kenosis (Priest)
on Dec 09, 2012 at 00:59 UTC ( #1007939=note: print w/replies, xml ) Need Help??

in reply to If conditional checks

Here's one way to do it, using the same logic you've used:

use strict; use warnings; use List::Util qw/sum/; my $host = 'db'; my @redAlert = ("db"); my @orangeAlert = ( "c", "sm" ); my %status = ( 'status_history' => { 'status' => [ 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 ] + } ); my $statusHist01 = sum @{ $status{status_history}{status} }[ 0 .. 1 ] +; my $statusHistTot = sum @{ $status{status_history}{status} }; if ( $host ~~ @redAlert or ( $host ~~ @orangeAlert and $statusHist01 == 2 ) or $statusHistTot == 3 ) { print "We've got a winner!"; }

The alerts are contained in arrays, so Perl's (v5.10+) smart operator (~~) can be used to check whether the value of $host is an element of either array. List::Util's sum is used to sum the relevant values from the status list.

Replies are listed 'Best First'.
Re^2: If conditional checks
by kitkit201 (Initiate) on Dec 09, 2012 at 05:14 UTC
    Thanks Superdoc, but I dont have perl 5.10 installed on my production system. is there any other way to do it? without the smart operator

      You can use grep instead of the smart match operator (~~):

      ... if ( grep /^$host$/, @redAlert or ( grep /^$host$/, @orangeAlert and $statusHist01 == 2 ) or $statusHistTot == 3 ) { print "We've got a winner!"; } ...

      grep iterates through all array elements, and in scalar context (as in this case), it returns the number of times an expression is true. Each expression in the greps is a regex that requires an exact match between the value of $host and an array element (contained in the default scalar, $_) to be evaluated as true.

        Thank you for the comment. One more thing about this is the host string. I see the host scalar to only work on the hostname if it only with db, but no other characters behind it, like db4323, how would you include it to have any other characters like periods and numbers, behind it? some example hostnames would be

      If you don't have Perl 5.10, you could try Perl 5.12, or Perl 5.14, or Perl 5.16. Or wait 6 months and try Perl 5.18.

      perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1007939]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (7)
As of 2018-06-24 22:49 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (126 votes). Check out past polls.