[prev in list] [next in list] [prev in thread] [next in thread] 

List:       ruby-talk
Subject:    Re: why won't ruby chomp for me?
From:       Sam Roberts <sroberts () uniserve ! com>
Date:       2004-01-29 15:25:59
Message-ID: 20040129152543.GC1682 () ensemble ! local ! 
[Download RAW message or body]

Quoteing emmanuel.touzery@wanadoo.fr, on Fri, Jan 30, 2004 at 12:04:30AM +0900:
> Hello,
> 
>    I was wondering.. IIRC, Perl came up with this "\n" in the end of 
> line in gets etc because in Perl, "" is false. So, if you want to have:

This is an interesting observation, but its not the reason. perl does it
like that because a line HAS a new-line character at the end (that's
what makes it a line).

> while (<>) {print $_;}
>    working, you needed that even empty lines won't be "false". So they 
> said that they will put the "\n" in the line, and problem is gone, nice 
> hack etc.

It's not a hack, its an anti-hack! perl, unlike awk (IIRC), tries not to
mangle your input data. What it read from the file is what it gives you.
This allows you to process binary files, for example, with perl -
whereas with awk/sed/grep etc., the assumption that input is always line
oriented, and thus that newlines should be stripped when reading a line,
for "convenience", makes this hard/impossible.

>    but in ruby, "" is true, so i'm wondering... why did ruby take this 
> over from perl? i find myself many times forgetting that chomp and the 
> fact ruby offers me the "raw" line format never ever helped me in any 
> way. is it just historical praise to Perl?

Even with text, the last line in a file may or may not end with a
newline character.

If you wanted to write out the file exactly as you read it, AND perl/ruby
auto-chomped any newlines, how would you know whether the last line had
a newline or not?

In your example above, if the newline was removed by <>, would you
expect the print to put it back? But print doesn't do that, and
shouldn't, what if you want to do two prints to build up a single line!

>    just curious,

Basically, removing the newline on input is the hack, just like adding
it on output is, and its only a useful hack if you are always doing line
oriented IO. perl (and ruby) is great for line-oriented processing, like
awk/sed/..., but unlike those others, they give you control over your
input and output, you aren't FORCED to do everything line-oriented.

Cheers,
Sam


[prev in list] [next in list] [prev in thread] [next in thread] 

Configure | About | News | Add a list | Sponsored by KoreLogic