Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation

Re: Problem with <STDIN>

by strat (Canon)
on Jun 28, 2006 at 09:18 UTC ( #557969=note: print w/replies, xml ) Need Help??

in reply to Problem with <STDIN>

Better don't use chop for removing newlines; chop just removes the last char which is ok for unix and linux but not for windows, because there the newline has two chars: CR + LF. Better use chomp which is aware of the different types of line endings

Best regards,
perl -e "s>>*F>e=>y)\*martinF)stronat)=>print,print v8."

Replies are listed 'Best First'.
Re^2: Problem with <STDIN>
by GrandFather (Sage) on Jun 28, 2006 at 09:45 UTC

    The important distinction with chomp is that it removes $/ from the end of each element in the list passed to it (nothing happens if an element is not terminated with $/).

    Chop removes the last character without regard to what the character is - chop always alters a non-empty element.

    Note in particular that line end differences between file systems have been papered over by this stage and the default value for $/ is \n (which may or may not be a line feed character; you don't need to know). Neither chop nor chomp know or care about file system line end differences.

    DWIM is Perl's answer to Gödel
Re^2: Problem with <STDIN>
by ikegami (Pope) on Jun 28, 2006 at 14:20 UTC

    No, that's completely wrong. chomp removes what's in $/ from the end of its arguments. $/ is equal to \n (by default) in Windows, so chomp only removes \n (by default) on Windows too.

    Perl translates CR+LF to LF for you when you read from a file in Windows (unless you use binmode on that handle). Similarly, Perl translates LF to CR+LF when writting to a file handle in Windows (unless you use binmode on that handle).

    The reason to use chomp is to handle the case where a line without the line terminator is read in. chop would fail to perform as desired there, but chomp wouldn't. That has nothing to do with CR+LF vs LF.

    Update: Added underlined text to clarify my intended message, at GrandFather's recommendation.

      It's not that chop fails, as it removes the last character regardless of what that character is. You could interpret that to mean that chop "fails to DWIM", but it hasn't failed, just not met the programmer's expectations.

      DWIM is Perl's answer to Gödel

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://557969]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (3)
As of 2018-01-19 07:05 GMT
Find Nodes?
    Voting Booth?
    How did you see in the new year?

    Results (216 votes). Check out past polls.