Beefy Boxes and Bandwidth Generously Provided by pair Networks DiBona
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: perl substitue till found pattern in aline

by rjt (Chaplain)
on Dec 02, 2012 at 18:33 UTC ( #1006742=note: print w/ replies, xml ) Need Help??


in reply to perl substitue till found pattern in aline

while (<DATA>) { s/ (?=.*\s?-1 )/,/g; print; } __DATA__ 01 fines name 2222 -P sws -1 reee.tee rrt 02 fi si 2232 -P sqww -1 re.wqw ttf 02 fi si-1 2232 -P sqww -1 re.wqw ttf

This will replace spaces with commas before the last -1 in the file.


Comment on Re: perl substitue till found pattern in aline
Download Code
Re^2: perl substitue till found pattern in aline
by pushtaev (Sexton) on Dec 03, 2012 at 06:26 UTC

    This variant is a little bit more easy to read and should be executed faster.

    while (<DATA>) { my ( $left, $right ) = split /-1/, $_, 2; $left =~ s/ /,/g; print join '-1', $left, $right; } __DATA__ 01 fines name 2222 -P sws -1 reee.tee rrt 02 fi si 2232 -P sqww -1 re.wqw ttf 02 fi si-1 2232 -P sqww -1 re.wqw ttf

      Hi!

      Your code is slower by about a factor of 3:

      use Benchmark qw/:all :hireswallclock/; my $DATA = '01 fines name 2222 -P sws -1 reee.tee rrt'; cmpthese(-10, { 'rjt' => q{ $_ = $DATA; s/ (?=.*\s?-1 )/,/g; }, 'pushtaev' => q{ $_ = $DATA; my ( $left, $right ) = split /-1/, $_, 2; $left =~ s/ /,/g; join '-1', $left, $right; }, });
      Rate pushtaev rjt pushtaev 1875006/s -- -75% rjt 7582716/s 304% --

      Regarding readability, it will depend who you ask in this case. In my experience, I tend to find a simple regex easier to read than tearing apart and piecing a solution back together with split, s///, and join.

      Lastly, in your code, replacing this:

          print join '-1', $left, $right;

      ... with this:

          print $left, '-1', $right;

      ... resulted in a 32% speed improvement before I/O on your solution (still ~2.2x slower than the straight regex) and puts the terms in their natural order, which is probably more readable than the strange use of join with a delimiter to concatenate three strings.

      I hope this is useful feedback to your feedback!

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1006742]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (11)
As of 2014-04-18 15:00 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    April first is:







    Results (469 votes), past polls