the output should be:andromeda:davidj perl_test > cat f.txt ^this^ ^is^ ^a^ ^test^ ^david#jenkins^ ^ cinea#jenkins ^
I currently have the following code which works perfectly well:andromeda:davidj perl_test > cat out.txt ^this^ ^is^ ^a^ ^test^ ^ddaavviidd#jjeennkkiinnss^ ^ cciinneeaa#jjeennkkiinnss ^
I didn't like the idea of creating a temporary string, so I have the following which modifies the text as it is processing it, and also works perfectly well:#!/usr/bin/perl use strict; open(FILE, "<f.txt"); open(OUT, ">out.txt"); while(<FILE>) { my $str = ""; chomp $_; if( 1 .. 4 ) { print OUT "$_\n"; next; } while( $_ =~ m/(.)/g ) { if( $1 =~ m/(\^|\#)/ ) { $str .= "$1"; } else { $str .= "$1$1"; } } print "$str\n"; print OUT "$str\n"; } close(FILE); close(OUT);
I don't like this solution because it breaks the cardinal rule of not modifying a for loop counter inside the loop. (Not that I'm any kind of coding purist, mind you :)#!/usr/bin/perl use strict; open(FILE, "<f.txt"); open(OUT, ">out.txt"); while(<FILE>) { chomp $_; if( 1 .. 4 ) { print OUT "$_\n"; next; } for( my $i = 0; $i < length($_); $i++ ) { if( substr($_, $i, 1) =~ m/(\^|\#)/ ) { substr($_, $i, 1) = "$1"; } elsif( substr($_, $i, 1) =~ m/(.)/ ) { substr($_, $i, 1) = "$1$1"; $i++; } } print OUT "$_\n"; } close(FILE); close(OUT);
Now to my curiosity: Both of these solutions work and I am satisfied with using either of them. What I'd like to have, purely for the educational value, is a more "Perlish" way of doing this, and/or a more efficient way.andromeda:davidj perl_test > perl test.pl Rate 2nd string In place 2nd string 28969/s -- -17% In place 35112/s 21% --
In reply to modifying a string in place by davidj
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |