Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi.

Is there a way I can remove line breaks '\n' from a variable?

Thanks,
Ralph.

Replies are listed 'Best First'.
Re: Removing Line Breaks
by MrNobo1024 (Hermit) on Mar 31, 2001 at 23:25 UTC
    If you only want to remove line breaks at the end of a variable, use
    chomp $variable;
    If you want to remove all line breaks, use
    $variable =~ tr/\n//d;
(jeffa) Re: Removing Line Breaks
by jeffa (Bishop) on Mar 31, 2001 at 22:48 UTC
    my $str = "hello world\n"; chomp $str; # pac man style - ooohhhh!! you think you know kung foo? # or $str =~ s/\n//; # for one \n $str =~ s/\n//g; # for all \n's
    Shameless plug: I just finished a column node 3 minutes ago on A Little History on 0D0A

    Jeff

    R-R-R--R-R-R--R-R-R--R-R-R--R-R-R--
    L-L--L-L--L-L--L-L--L-L--L-L--L-L--
    
Re: Removing Line Breaks
by Xxaxx (Monk) on Apr 01, 2001 at 02:48 UTC
    Be sure to take a moment and savor the \r\n issue raised by jeffa in his shameless node promo (well written by the way).

    The \r from window's text files can jump up and bite ya on the rear if you're not paying attention.

    Depending on where your data is coming from, it can have that extra \r in it.
    I was recently surprised to realize that txt files uploaded using

    <form action="blahblahscript.pl" method="POST" enctype="multipart/form-data">
    and <input type=file name="upload_filename">

    contained \r. Of course it's obvious they would when considered. However, I'd been running along for days without considering it. ;-)

    Moral of the story. Sometimes, depending on where your data is coming from, you may want to do a little cleanup to remove window's weirdness so it doesn't clutter up your nice linux environment.

    Claude