[ABE.pm] perl regex Q

Ricardo SIGNES rjbs-perl-abe at lists.manxome.org
Tue Dec 14 16:16:26 CST 2004


* Faber Fedor <faber at linuxnj.com> [2004-12-14T16:45:33]
> so I did this:
> 
>     perl -iBAK -p -e 's/,,/,\\N,/g' foo.txt
> 
> Unfortunately, that creates a file that looks like this
> 
>     1.2,3.4,\N,5.67,78.9,\N,,\N,,0.01
> 
> It looks like after the replace, the search starts at the next character
> after the previous search  term.  How do I get around that? There's
> prolly a magical switch for that, but I can't find it.
 
You told it: find two commas, replace them with ",\N," and then keep
going.  Well, it keeps going from the last thing it found: the second
comma.  What you want to say is:  find a comma; if the next thing is a
comma, replace the comma you found with ",\N" and keep going.

 $string =~ s/,(?=,)/,\\N/g

The (?= ... ) construct is called a look-ahead assertion.  It asserts
that something occurs ahead of the current point in the regexp.
Understanding how to use look-around is something that many Perl
programmers never really get to, which is a bummer, because it's way
fun.

A less elegant solution would have been:

	while ($string =~ /,,/) {
		$string =~ s/,,/,\\N,/g;
	}

This would keep applying the replacement until it found every case.
 
> Also, is there a way to do a perl "edit in place" inside of a perl
> program other than using backticks (`perl -iBAK -p -e 's/,,/,\\N,/g'
> foo.txt`) or the system() call?

No.

Well, yes, but you won't like it!

Consult "perldoc perlrun" and look under the section about -i;  it
explains how -i would be implemented in Perl, more or less.

> (No, reading the file in a line at a time is not an option.)

Why not?  It's what perl does when you use -i.

Give us more real-world information about what you need to accomplish,
and what the limitations are.

-- 
rjbs
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: not available
Url : http://mail.pm.org/archives/abe-pm/attachments/20041214/01cf8730/attachment.bin


More information about the ABE-pm mailing list