Ming has asked for the wisdom of the Perl Monks concerning the following question:

This code doesn't delete the first line when passed a parameter of delete=0. It works for all other values. How come?
use CGI qw(:standard); if(param('delete')) { $lineNum = param('delete'); open(FILE, "$filename"); @lines = <FILE>; close(FILE); splice(@lines, $lineNum, 1); open(FILE, ">$filename"); print FILE (@lines); close(FILE); }

Replies are listed 'Best First'.
Re: CGI parameter of 0 behaving strangely
by hardburn (Abbot) on Jun 12, 2003 at 15:48 UTC

    Because when delete=0, then param('delete') returns 0. When evaluated in boolean context (which is what if does), 0 is false and all other values are true.

    I think what you want is if(defined param('delete')) { . . . }. defined() returns true if the value given is actually defined, but doesn't care what it was defined as.

    ----
    I wanted to explore how Perl's closures can be manipulated, and ended up creating an object system by accident.
    -- Schemer

    Note: All code is untested, unless otherwise stated

      I see... thank you.
Re: CGI parameter of 0 behaving strangely
by edan (Curate) on Jun 12, 2003 at 15:48 UTC

    Because in perl, zero ('0') is false, so the 'if' test fails.

    --
    3dan