in reply to Help understanding a single line of perl: my $count = $row[0] ? $row[0] : 0;

?: is the conditional operator. See perlop for documentation. In short,
cond ? then_expr : else_expr
is similar to
if (cond) { then_expr } else { else_expr }

except it can be used inside another expression. It returns the value of then_expr or else_expr as appropriate. That means

my $count = $row[0] ? $row[0] : 0;
is short for
my $count; if ($row[0]) { $count = $row[0]; } else { $count = 0; }

Update:

It could also have been written as

my $count = $row[0] || 0;

It seems to me it's trying to avoid assigning undef to $count, using zero instead when the situation occurs.

Replies are listed 'Best First'.
Re^2: Help understanding a single line of perl: my $count = $row[0] ? $row[0] : 0;
by Tanktalus (Canon) on Aug 21, 2009 at 18:50 UTC

    Well, it's probably closer to:

    my $count = do { if ($row[0]) { $row[0]; } else { 0 } };
    but that's less readable to the uninitiated than what you have. :-P

      if already returns the right thing. It's simply a parser check that prevents it from being used as an expression. (But I guess you know that.)

      I would have used do if it would have made it equivalent, but since it didn't, it was more readable to explain do rather than using do.

Re^2: Help understanding a single line of perl: my $count = $row[0] ? $row[0] : 0;
by kdmurphy001 (Sexton) on Aug 21, 2009 at 18:59 UTC
    Ah, yes that makes sense. I added a CASE statement to the sql statement but I think that was unnecessary. Thank you so much!