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

Greetings, esteemed monks!

Is one of these superior to the other, and if so, why? given

use strict; my $contents = param("$a");
which is better?
my @contents = split( /\n/, $contents ); $contents = join( "<br>", @contents );
or
$contents =~ s/\n/<br>/g;
?

_________________________________________________________________________________

I like computer programming because it's like Legos for the mind.

Replies are listed 'Best First'.
Re: Is one form of character substitution better than the other, and if so, why?
by Fletch (Bishop) on Aug 21, 2006 at 15:28 UTC

    As always, when in doubt Benchmark. But the substitution's likely going to be the quickest as it won't have the overhead of building the temporary array @contents that's (presumably) thrown away after the join is done.

Re: Is one form of character substitution better than the other, and if so, why?
by imp (Priest) on Aug 21, 2006 at 15:37 UTC
    For the example you provided the regex approach will run faster and be easier to read. I tend to prefer intuitive code over fast code except when it really matters.

    To satisfy your curiosity you can play with the Benchmark module, which turnstep wrote a tutorial for in this node.

    As you benchmark more of your code you may find yourself committing one of the cardinal sins - premature optimization.

      Thanks, I have to look into premature optimization...it sounds like the kind of thing about which a woman might tell me "It's OK, it happens to everybody."

      _________________________________________________________________________________

      I like computer programming because it's like Legos for the mind.

        I wouldn't want to be found around women who know what happens to everybody.

        CountZero

        "If you have four groups working on a compiler, you'll get a 4-pass compiler." - Conway's Law

Re: Is one form of character substitution better than the other, and if so, why?
by OfficeLinebacker (Chaplain) on Aug 25, 2006 at 14:40 UTC
    Greetings, esteemed monks!

    Well, after looking around, the regexp is my preferred method. I ended up doing this:

    my $contents = param("$a"); $contents =~ s/(\n|\r)/<br>/g; $contents =~ s/(<br>)+/<br>/g;
    I suppose you can imagine by now what this is for!

    Thanks again!

    Terrence

    _________________________________________________________________________________

    I like computer programming because it's like Legos for the mind.