Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Comparing 3 vars if defined.

Status
Not open for further replies.

brittany1

Technical User
Aug 17, 2007
12
US
I have a scripting problem .. not sure where to start.

I will have 3 vars. They could or could not be defined. For any defined var, I need to check that the string is identical to other define vars.

So for example I could have :
$x=NOW IS THE TIME
$y=NOW IS THE TIME
$z=NOW IS THE TIME

OR
$x=NOW IS THE TIME
$y=
$z=Now ISnt THE TIME

or

$x=NOW IS THE TIME
$y=
$z=

or any other combination thinkable.

Thanks in advance
 

Thank Keith .. sheez .. now that I see it, it looks too easy ... should have been able to figure that out. Guess sometimes I just become blind ... cant "see" it ... thanks again.
 
The problem with audiopro's solution is that it only works when all three values are defined. As I understand it, you want to pick cases where all defined values are identical, and ignore undefined values. So the first and last of the three cases you listed should pass, whilst the middle one should fail.

I haven't tested it, but something like this should do:
Code:
if ((($x eq $y) || ($x eq '') || ($y eq ''))
 && (($x eq $z) || ($x eq '') || ($z eq ''))
 && (($y eq $z) || ($y eq '') || ($z eq ''))) then
   # They match
}

-- Chris Hunt
Webmaster & Tragedian
Extra Connections Ltd
 
I assumed that the vars would be declared at the start of the script.
My latest offering would be.
Code:
my $x='';
my $y='';
my $z='';
if(($x ne '') && ($x) && ($y) && ($z) && ($x eq $y) && ($x eq $z)){
# They match
}



Keith
 
This should give you what you desire.

Code:
my @defined_vars = grep {defined $_} ($x, $y, $z);

if (@defined_vars && ! grep {$_ ne $defined_vars[0]} @defined_vars) {
    print "All Vars equal each other if they are defined\n";
}

The only special case that you didn't specify is what should happen if none of them are defined.

- Miller
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top