2
\$\begingroup\$

I'm not used with perl but had the need to add a couple of features, I wish I can adopt a more perl-ish coding.

Any help is welcome.

This is to add style classes to paragraphs if strarting with !, ? and a clear: both with %

Original:

foreach (@grafs) {
    unless (defined( $g_html_blocks{$_} )) {
        $_ = _RunSpanGamut($_);
        s/^([ \t]*)/<p>/;
        $_ .= "</p>";
    }
}

Modded:

foreach (@grafs) {
    unless (defined( $g_html_blocks{$_} )) {
        $_ = _RunSpanGamut($_);
        if ( m/^[ \t]*\?/ ){
            s/^([ \t]*\?[ \t]*)/<p class="Introduction">/;
        } elsif ( m/^[ \t]*\!/ ){
            s/^([ \t]*\![ \t]*)/<p class="Important">/;
        } elsif ( m/^[ \t]*%/ ){
            s/^([ \t]*%[ \t]*)/<p style="clear: both;">/;
        } else {
            s/^([ \t]*)/<p>/;
        }
        $_ .= "</p>";
    }
}

This is to add float to images like: !<[alt](url) to get a float right (and form this the % above to clear)

if (defined($align)) {
    if ($align eq "<") {
        $result .=  " style=\"float: left; margin: 0 ${padding}px ${padding}px 0;\"";
    } else {
        $result .=  " style=\"float: right; margin: 0 0 ${padding}px ${padding}px;\"";
    }
}
\$\endgroup\$
1
  • \$\begingroup\$ If you can I would move towards using Markdent, which is easier to extend. \$\endgroup\$ Jul 31, 2012 at 23:43

1 Answer 1

3
\$\begingroup\$

Note that a substitution only occurs if there is a match, and then it will return the number of substitutions it makes. This means that a true value is returned if a match/substitution happens.

With that in mind, you don't need the m/.../ in addition to the substitution. You can also make use of or to achieve the short-circuiting that you had with the if ... elsif ... else ... statements.

foreach (@grafs) {
    unless (defined $g_html_blocks{$_}) {
        $_ = _RunSpanGamut($_);
        s/^([ \t]*\?[ \t]*)/<p class="Introduction">/
            or
        s/^([ \t]*\![ \t]*)/<p class="Important">/ 
            or
        s/^([ \t]*%[ \t]*)/<p style="clear: both;">/
            or
        s/^([ \t]*)/<p>/;
        $_ .= "</p>";
    }
}

For the image floating, you could use a hash instead of if ... else ...:

my %float = (
    '<' => 'float: left',
    '>' => 'float: right',
    '%' => 'clear: both'
);
if (defined $align) {
    $result .= " style=\"$float{$align}; margin: 0 ${padding}px ${padding}px 0;\"";
}

A minor point: I also removed the parens from the defined checks because they're not needed and it gives you a little more white space to reduce a little clutter.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.