Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery

Re: Re: Redefining chomp()

by ryantate (Friar)
on Mar 24, 2004 at 18:28 UTC ( #339501=note: print w/replies, xml ) Need Help??

in reply to Re: Redefining chomp()
in thread Redefining chomp()

As there is no quantifier on your character class, I have trouble understanding how this will remove multiple newlines as you say. Am I missing something?

Also, if the Windows newline is in fact "\r\n", this will not work, again because there is no quantifier.

It seems to me if you instead do

$count += $_ =~ s/\r?\n$//g;

... then you alleviate the problem of killing all trailing newlines and, assuming "\r\n" is what all windows newlines are, you are matching both windows and unix newlines.

Replies are listed 'Best First'.
Re: Re: Re: Redefining chomp()
by Limbic~Region (Chancellor) on Mar 24, 2004 at 18:42 UTC
    My regex fu is non-existant as you can see. That does not really matter much as I said it would need to be fixed. I was on my way to a meeting so I didn't get to spend a lot of time on it. After thinking about it some more, I think the following would work a lot better.
    package Chomp; use Scalar::Readonly ':all'; BEGIN { *CORE::GLOBAL::chomp = sub { readonly_on( $/ ); my ($count, $fix) = (0, ''); local $/ = "\r\n"; for ( @_ ) { my ($first, $second) = (0, 0); eval { $first = chomp }; if ( $@ ) { die $@ if $_ !~ /^\r?\n$/; $fix = $_; last; } if ( ! $first ) { local $/ = "\n"; $second = chomp; } $count += $first + $second; } readonly_off( $/ ); return $fix ? ($count , $fix) : $count; }; } 42; # Then a script that uses it #!/usr/bin/perl use strict; use warnings; use Chomp; my $foo = "foo\n\r\n"; my $bar = "bar\n\n\n"; print chomp $foo, $/; # prints 2 print chomp $bar, "\n"; # prints 1 print chomp ($foo, $bar), "\n"; # prints 2
    This does have the unfortunate side effect of not allowing someone to do:
    chomp($/); # $/ = undef;
    I know this is ugly and there are probably a few more gotchas in there, but It was kind of fun to work on. Note: This can be done without a module, but it is much uglier. Anyone wanting to see that should say so.

    Cheers - L~R

Re^3: Redefining chomp()
by Roy Johnson (Monsignor) on Mar 24, 2004 at 18:48 UTC
    I have trouble understanding how this will remove multiple newlines as you say. Am I missing something?
    If the trailing /g on an anchored s///g actually had some effect, maybe it would strip off all trailing newlines. But as it is, it doesn't.

    The PerlMonk tr/// Advocate

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (6)
As of 2019-07-18 10:49 GMT
Find Nodes?
    Voting Booth?

    No recent polls found