in reply to Problems printing to browser
Just a point of preference but:
Try replacing:
With:
Try replacing:
my $tags =''; if ($form{'abstract'} ne "") { $tags .= qq(<meta name="abstract" content="$form{'abstract'}"><br +>\n); } if ($form{'author'} ne "") { $tags .= qq(<meta name="author" content="$form{'author'}"><br>\n) +; } if ($form{'distributor'} ne "") { $tags .= qq(<meta name="distributor" content="$form{'distributor' +}"><br>\n); } if ($form{'copyright'} ne "") { $tags .= qq(<meta name="copyright" content="$form{'copyright'}">< +br>\n); } if ($form{'keywords'} ne "") { $tags .= qq(<meta name="keywords" content="$form{'keywords'}"><br +>\n); } if ($form{'description'} ne "") { $tags .= qq(<meta name="description" content="$form{'description' +}"><br>\n); } $tags .= qq(<meta name="generator" content="SpyderTagV1.0!"><br>\n); if ($form{'robots'} ne "") { $tags .= qq(<meta name="robots" content="$form{'robots'}"><br>\n) +; } if ($form{'language'} ne "") { $tags .= qq(<meta name="language" content="$form{'language'}"><br +>\n); } if ($form{'distribution'} ne "") { $tags .= qq(<meta name="distribution" content="$form{'distributio +n'}"><br>\n); } if ($form{'rating'} ne "") { $tags .= qq(<meta name="rating" content="$form{'rating'}"><br>\n) +; } print my $cgi->escapeHTML( $tags);
With:
print my $cgi->escapeHTML( join '', ( map{ defined($form{$_}) ? qq(<meta name="$_" content="$form{$_}"><br> +\n):'' } qw ( abstract author distributor copyright description robots language distribution rating ) ),'<meta name="generator" content="SpyderTagV1.0!"><br>\n' );
Explanation
This uses the functional programming idiom, so start from the inner-most loop and work back.
- Use the qw function to produce an array of string items for everything in brackets. In this case a list of all the names of the elements from the %form hash
- Use the map function to process each element of the array produced by 'qw'. Map makes a list of all the results in order.
- Using a ternary operator to return a value: the string if the form item is defined, no text if not.
- Join all the array elements from the 'map' function. Also join the string outside the brackets for the map function.
- Finally print the escapeHTML'd version of the returned string from the join.
- Use single quotes where possible, ie where variables don't need to be interpolated.
One of the first things I learnt in Perl was to recognise repetitive patterns and then get rid of them.
I'm lazy.
A by product is if you want to add more meta fields it's easier now :)
--
Brother Frankus.
¤
In Section
Seekers of Perl Wisdom