Perl Warts

misfeatures and other problems
PERL| PHP| PYTHON| RUBY
Answers: (all questions)
Answer 1: (question)
Question:
#!/usr/bin/perl

foreach $x (1,2,3,4,5) {
  print "x: $x\n";
  if ($x > 2) { print "break\n"; break; }
}
Answer:
The program prints:
x: 1
x: 2
x: 3
break
x: 4
break
x: 5
break
The break operator does not do the same thing as in C or Python. Use last instead. Similarly, use next instead of continue.
Answer 2: (question)
Question:
#!/usr/bin/perl

$x = "moo";
if ($x == "") { print "Please supply input.\n"; }
else { print "You wrote '$x'\n"; }
Answer:
This program prints "Please supply input.".

The == operator in Perl does not compare strings. So, unexpected values may evaluate as equal. For example, 0 == "moo" is true, as is "moo" == "ribbit".

Use the eq operator to compare strings instead. Or, if you don't know the type of the objects you're comparing, compare their type first and then if they're the same, compare values with an appropriate operator.
PERL| PHP| PYTHON| RUBY
Last modified: March 30, 2006 @ 6:47 MST
Copyright (C) 1996-2024 Selene ToyKeeper