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 SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Very basic string conditional question... 2

Status
Not open for further replies.

Jakobud

Technical User
Mar 9, 2001
51
0
0
US
So I am just picking up Perl to learn and this simple string conditional is boggling my mind. Where is my syntax incorrect?

my $var = "hello";

if ( $var == "goodbye" )
{
print "goodbye everyone!";
}
else
{
print "no goodbye's today";
}


my output:
goodbye everyone!


What is up with that? $var != "goodbye"... but the script seems to think it is. I have not had this trouble with ints and floats, so I am assuming this is something to do with my string syntax regarding where to use quotes properly.

Anyways, can anyone tell me what I am doing wrong?
 
Ah... I think i just figured it out... guess I shoudl have continued reading to the next section...

== is a numeric-only thing I guess. But for strings you have to use "eq". That seems odd that in Perl, it's smart enough to figure out what type your variables are, but not smart enough to use interchangeable operators between them. Oh well.
 
Don't forget that the oposite to your numerical match '==' is '!=' and the opposite to matching non-numerical is 'ne'

Also, if your string contains something like:
Code:
$var = 'Hello Rob';
You can match it using:
Code:
if ($var =~ /Goodbye/i)  {
   print 'Goodbye everyone\n";
}  elsif ($var !~ /Goodbye/i)  {
   print 'No goodbyes today\n';
}
Basically it checks whether the string contains goodbye, the 'i' at the end tells it to disregard case.

Rob Waite
 
It's even smart enough to figure out that if you use an array in a scalar context, like
Code:
for (my $i = 0;$i < @columns;$i++)
what you really mean is that you want the size of the array, not the contents.

So why it makes a difference between == and eq is beyond me.
 
To get rid of ambiguity I suppose.

these two strings

' 100'

and '100'

When converted to the number they represent, they're equal. They are not equal as strings though.

Mike

To err is human,
but to really foul things up -
you require a man Mike.

Want to get great answers to your Tek-Tips questions? Have a look at faq219-2884

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top