xsznix
xsznix

Reputation: 2575

Perl if not working?

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.

Upvotes: 2

Views: 4028

Answers (2)

Cameron
Cameron

Reputation: 98746

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.

Upvotes: 14

tchrist
tchrist

Reputation: 80384

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

Upvotes: 2

Related Questions