Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

How do you chomp your chomps?

by kaatunut (Scribe)
on Jan 09, 2001 at 02:08 UTC ( [id://50578]=perlquestion: print w/replies, xml ) Need Help??

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

    This safer version of the chop entry elsewhere in
    this document removes any trailing string that
    corresponds to the current value of `$/' (also
    known as $INPUT_RECORD_SEPARATOR in the `English'
    module). It returns the total number of
    characters removed
    from all its arguments.

Suppose you're prompting user to say something:

print "Do you prefer foo or bar? [foo]"; if (chomp($_=<STDIN>),$_ and $_ eq "bar") { print "A fine, if a bit non-traditional, choice.\n"; } else { print "Do you know the origin of word 'foo'? So do we.\n"; }

That's how I would implement it, if the behaviour would have to be just that; if user types exactly "bar", then that, otherwise "foo". Would you do the same?

Assuming you would, here's my gripe; why does chomp act like that, modifying the argument instead of returning the changed value? Right away I can't think of any function (well, chop ...) besides chomp which prefers to change an argument instead of using a return value. It seems clumsy, too; as you can see from above example, you need a named temporary variable and a separate command to clean it. So much cleaner would sound, chomp(<FILE>) eq "bar", to me, at least.

And for what benefit is it like that? Return value, number of characters chopped ... is essentially a boolean, since return value is either 0 or length($/) (unless, of course, we're going to get RE $/ some day...). Well, that information is useful in its way too, I suppose, but every context I've so far used chomp in would have needed the mutilated value rather than the information whether it was chomped. I use chomp only to make sure variables are clean, I don't care whether they were dirty before. Do you?

Did I miss something essential here, or is this just some relic from days long past?

P.S. That this is in Seekers instead of Meditations should point you out that that last sentence is not rhetorical.

Replies are listed 'Best First'.
(tye)Re: How do you chomp your chomps?
by tye (Sage) on Jan 09, 2001 at 03:10 UTC

    chomp is based on chop and chop modifies in place so that it can return the character that was chopped, so it makes some sense to have chomp also modify in place since it just a "safer chop". chomp can also work on a list of items, in which case the return value is more than a Boolean.

    Also, shortening a string in place is extremely efficient. To return a modified value would require allocating another buffer and copying nearly the entire string.

    There are several operations that modify in place: s///, tr///, read(), sysread(), etc. For most of them, I've run into cases where I'd rather have them return the modified value so I do see your point. But the inconvenience is fairly minor -- we just get used to not having to up with even minor inconvenience because we are using Perl. (:

    Also, if it only returned the modified value (and didn't also modify in place), then you'd constantly be writing $input_line= chomp($input_line) and requiring the repetition isn't good. If it modified in place and returned the modified value, then there'd be no good way to tell if a modification took place.

    So it's a mixed bag. :-}

            - tye (but my friends call me "Tye")
      And, of course, one could always write their own little function such as:
      sub my_chomp { my $str = shift; chomp($str); return $str; }
      Though this doesn't handle arrays, it also doesn't modify the input string in place.
        Well, heck. If we're gonna go that route, may as well golfuscate it:
        sub my_chomp { substr shift, 0, (length) - 1 if $_[0] =~ /\n$/}; # :-)

        Cheers,
        Ovid

        Update: Can anyone tell that I am *seriously* bored at work?

        sub my_chomp { wantarray ? (map{ /\n$/ ? substr $_, 0, (length)-1 : $_ + } @_) : chomp(my $x = shift),$x };
        That ugly hack will work for both arrays and scalars (I think). I noticed that it appears to be returning an empty element at the end of the array, though. :(

        Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.

(Ovid) Re: How do you chomp your chomps?
by Ovid (Cardinal) on Jan 09, 2001 at 03:02 UTC
    Personally, I have never used the return value from chomp, but that's not to say it's useless. Did you know you can chomp an array?
    my @array = ( "one\n", "two\n", "three", "four\n" ); my $result = chomp @array; print $result, $/; print @array;
    In that snippet, $result is set to 3 and all elements of the array have had their trailing newline removed. Offhand, I don't see the utility of chomp returning the number of elements chomped, but I also remember that when I first started programming, I didn't see the utility of the ternary operator ( y = x ? y : x ). Now, I use it all the time.

    chomp itself is very useful when I pull in data from a variety of sources and do something with them. I usually don't want a bunch of newlines unless I put them there.

    Cheers,
    Ovid

    Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.

Re: How do you chomp your chomps?
by extremely (Priest) on Jan 09, 2001 at 03:00 UTC
    It isn't always length $/; that it returns. In $/=""; it might chomp multiple returns and if used on a list it counts all the whacking that it does.

    --
    $you = new YOU;
    honk() if $you->love(perl)

Re: How do you chomp your chomps?
by dchetlin (Friar) on Jan 09, 2001 at 16:58 UTC
    I try to hide it, but my first love was Dylan and I'm a functional programmer at heart. It often frustrates me that I can't use the return values of chomp, s, pop, etc. to chain operations/functions.

    Had I the capability to turn back the clock and influence Larry in his language decisions, I would vote for the operators like the above to return the value that they now modify in place, and for each to have a bang complement (e.g. chomp!) that works the way the current ones do. Ruby does this to some extent.

    tchrist has been known to say similar things, based on his observations of what people new to the language expect. See, for example, this perl6 post. I can't see a change like this really happening -- it would affect too many scripts.

    -dlc

Re: How do you chomp your chomps?
by kaatunut (Scribe) on Jan 09, 2001 at 02:11 UTC
    P.S. Don't say anything about scalar/list context in my imaginary chomp(<FILE>) example. I should learn to proofread better.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://50578]
Approved by root
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chilling in the Monastery: (5)
As of 2024-03-29 08:26 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found