2

Here is my code:

#!/usr/bin/env perl

sub start
{
    ...
}

sub stop
{
    ...
}

if (defined $ARGV[0])
{
    if ($ARGV[0]=='start') {start}
    elsif ($ARGV[0]=='stop') {stop}
    else {die "Unrecognized command: $ARGV[0]"}
}

Whatever I do though, it always executes &start. Am I doing something wrong?

I'm using Linux Mint 10 and Perl 5.10.1.

Axeman
  • 29,660
  • 2
  • 47
  • 102
xsznix
  • 2,535
  • 2
  • 17
  • 14

2 Answers2

14

You're using numeric comparison to check string equality, which converts the arguments to numbers first before comparing them.

In this case, 'start' is not a number, so it gets converted to 0; the value in $ARGV[0] (which is expected to be a word here) is also converted, resulting in another 0 and a final condition of if (0 == 0), which is always true.

You want to use the eq string-wise comparison operator instead:

if ($ARGV[0] eq 'start') { start }

See the docs for more information on the different comparison operators.

Note that (as has been pointed out in the comments) including use warnings; at the top of your script would have caused perl to warn you about this from the start. Always including use warnings; and use strict; is generally best practice, as it helps catch these kinds of errors early.

Cameron
  • 96,106
  • 25
  • 196
  • 225
  • 9
    Treated as a number, 'start' is the same as 0, and so are most other strings. Using `use warnings; use strict;` would help. – Jonathan Leffler Feb 04 '11 at 17:23
  • 2
    Indeed, with strict and warnings turned on, the problem would pop out right away with a relevant warning message. – Ether Feb 04 '11 at 17:29
  • you should add that his first condition is actually `if ( 0==0 )` which is pretty self-explanatory. – Axeman Feb 04 '11 at 19:50
  • @Axeman: I'll add it in my answer, but Jonathan's comment speaks for itself – Cameron Feb 05 '11 at 00:18
  • @Jonathan: +1. Adding to your comment: A string starting with a number (like `'1234abc'`) would be converted to that number (`1234`), and anything else is converted to `0` – Cameron Feb 05 '11 at 00:38
2

The bug is that your program neglected to start with the standard boilerplate for Perl code.

Community
  • 1
  • 1
tchrist
  • 78,834
  • 30
  • 123
  • 180
  • The bug is using Perl in the first place. I always thought Perl was a write only language. The question teaches me otherwise... – Ber Feb 05 '11 at 00:45