Perl Single line IF statement blocks?

  • Tdotwire
  • Proficient
  • Proficient
  • User avatar
  • Posts: 486
  • Loc: Toronto

Post 3+ Months Ago

I have just reciently began to study the Perl language. I came across a rather annoying fact that single line IF statements are not possible. I may be incorrect here since I am very new to the language, but what I have noticed is that the following code block would result in an error...

if($a=="a")
$b = "ok";

now, is there any way to make this work as a single line, or do I have to use the braces?
  • Mas Sehguh
  • Mastermind
  • Mastermind
  • User avatar
  • Posts: 1853

Post 3+ Months Ago

In Perl you have to use the braces. It's really a good idea to be using them anyway, even in languages where you can't, or at least I'm in that habit (thanks to Perl, really).

Then again, in Perl, you can place an if statement at the end of a single line:

Code: [ Select ]
$b = "ok" if $a eq "a";


(note that ==, <, >, <=, >=, !=, and <=> do numerical comparison in Perl. You'll want to use eq, lt, gt, le, ge, ne, and cmp for string comparisons.)
  • Tdotwire
  • Proficient
  • Proficient
  • User avatar
  • Posts: 486
  • Loc: Toronto

Post 3+ Months Ago

ok great, guess Perl acts like java when it comes to string comparison

Is there a ignorecase comparison, just like Java has the str.compareIgnoreString("string"); method?

or when comparing strings, should I just make both strings the same case?
  • Mas Sehguh
  • Mastermind
  • Mastermind
  • User avatar
  • Posts: 1853

Post 3+ Months Ago

Nah, Perl strings will automatically get converted to numerical form of you compare them with ==. Hence "3" == 3, "3.00000" == 3, "3.00000" == "3", and "3" == "+3" will all return true. Also, so will 3 == "3 blah blah". And "a" == "wxyzk" will return true, because "a" == 0 == "wxyzk".

If you want to ignore case, use the lc function to convert to lowercase. I.e.

Code: [ Select ]
if (lc "Khan!!!" eq lc "KHAN!!!") { print "foo\n" }
  • eggi
  • Novice
  • Novice
  • eggi
  • Posts: 30

Post 3+ Months Ago

You can ignore case when comparing variables using the regular expression comparison operator =~ (or the opposite compare: !~)

e.g. if ( $a =~ /Ok/i )

Note that this will match ok, ignoring case in any part of whatever $a represents, so it will return true of $a is "ok" or "dokey". If you want to restrict it to a word, use \b within the regular expression to "bookend" either, or both, sides of the match term.

, Mike

Post Information

  • Total Posts in this topic: 5 posts
  • Users browsing this forum: No registered users and 70 guests
  • You cannot post new topics in this forum
  • You cannot reply to topics in this forum
  • You cannot edit your posts in this forum
  • You cannot delete your posts in this forum
  • You cannot post attachments in this forum
 
cron
 

© 1998-2014. Ozzu® is a registered trademark of Unmelted, LLC.