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

I would like to add a condition to a cell in a table. I was looking at doing something like this: <td bgcolor='if ($ref->{'status'} == 'open') { "blue";} else {"green"; } '> As already knew this is returning an error. Can somebody help? Thanks.

Replies are listed 'Best First'.
Re: Conditional statement in HTML code.
by Eily (Monsignor) on Feb 06, 2018 at 18:27 UTC

    It depends on how you are building your HTML page. Are you just using strings or are you using some templating system? My guess would be for the latter, but you'll have to tell us which one.

    And that's assuming you want this code to be executed on server side, not client side (ie: the color doesn't change after the page is loaded).

    Edit: relying on the return value of if/else isn't very good style IMHO. But you can use the ternary operator instead which works like that: CONDITION ? VALUE_IF_TRUE : VALUE_IF_FALSE;, so in your case: my $bgcolor = ($ref->{'status'} == 'open') ? 'blue' : 'red'

      It's not a template. I'm just using the PERL print command to spit out the HTML code. The code will executing on the server, which I believe is default for CGI.

        The code to build the page is on the server side by default (and in pretty much all sane cases I guess?) yes, but you can have some code to change the page dynamically when displaying it.

        If that's just a string, you can use interpolation. You should first put the value in a variable and then interpolate, not only is this clearer, but it's also easier to do:

        my $bgcolor = ($ref->{'status'} == 'open') ? 'blue' : 'red'; print "<td bgcolor='$bgcolor'>";