Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re: return value of chomp is false?

by toolic (Bishop)
on Sep 29, 2009 at 01:37 UTC ( [id://798034]=note: print w/replies, xml ) Need Help??


in reply to return value of chomp is false?

I would have thought that the return value of a successful chomp would be interpreted as "true", but it appears that it returns false.
According to the documentation for chomp:
It returns the total number of characters removed from all its arguments.
If there is no newline, for example, it returns 0; if there is a newline, it returns 1.

So, chomp $_ will return 1, which is true, which causes the ternary operator to return the 'true' result. In your non-working case, it returns the empty string. In your working case, it returns the $_ without the newline.

Replies are listed 'Best First'.
Re^2: return value of chomp is false?
by babel17 (Acolyte) on Sep 29, 2009 at 16:56 UTC
    But there is always a new line, so it should always be interpreted as true, which means the first case should work, not the second case. ...but that is not the case. The chomp is returning '1' and it's being interpreted as false.
      Let me try to elaborate on my answer.

      Firstly, here is a quote from the documentation for the Conditional Operator:

      Ternary "?:" is the conditional operator, just as in C. It works much like an if-then-else. If the argument before the ? is true, the argument before the : is returned, otherwise the argument after the : is returned.

      Coming from the STDIN handle, I agree that $_ will have a newline character. This means that chomp $_ will return 1. Since Perl treats 1 as a true value, the ternary operator will return the argument before the :.

      In your first case, chomp $_ ?"":$_, the ternary operator returns an empty string.

      In your second case, chomp $_ ?$_:"", the ternary operator returns $_.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others musing on the Monastery: (6)
As of 2024-04-16 06:55 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found