Perl Carrage Returns

Jason Parker-Burlingham jasonp at uq.net.au
Thu Dec 12 17:05:02 EST 2002


"Justin Bennett" <Justin.Bennett at dynabrade.com> writes:

> >> For all those Perl Gurus out there, I have a perl script I wrote It
> >> takes input from a form and loads it into an oracle database. I'm
> >> looking to strip the ^M s out of the large comment field that a
> >> windows browser puts in. I can't seem to get the character to match.
> >> Any ideas.
> >> Something like
> >>
> >> $text =~ s/^M//g;
> >>
> >> But I can't seems to generate a ^M that works ideas?

> Got it to work with the VI command. Nice thanks alot.

This is such a frequent question I feel it would be helpful to present
a full Perl program as an answer and dissect it fully:

        $ perl -i~ -pe'y/\015//d' file1 file2

The -i option turns on perl's "in-place edit" mode and the ~ indicates
that this should be used for creating a suffix for backup files; the
-p option turns on Perl's autoprinting behaviour, and the code
supplied as an argument to -e will delete all ASCII 015 (or \r
characters[1]) from the input stream before the implied print
statement.

The transliteration operator, y///, is used instead of the regex
substitution operator, s///, because it is more well-suited to the
task; there's no need to invoke the whole regular expression engine
for something so simple.  The trailing d option to y/\015//d indicates
that the matched characters should be deleted instead of replaced with
nothing (ie left alone).  See man perlop for details.

This program will happily work on multiple input files, as above, or
as a command-line filter.  To use something similar in a program:

	sub trim_control_ems {
	        my $text = shift;
	        $text =~ y/\015//d;
	        return $text;
	}
	
	# main program, we've collected the browser input already and
        # want to clean it up.
	
	trim_control_ems($MS_browser_input);

[1] : See ASCII(7) for details.
-- 
||----|---|------------|--|-------|------|-----------|-#---|-|--|------||
| ``I think I'm going to throw up.''                                    |
|                                             -- Kermit the Frog, Yambo |
||--|--------|--------------|----|-------------|------|---------|-----|-|



More information about the nflug mailing list