Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Question why my code is posting a new line

by chiggly007 (Initiate)
on Dec 18, 2012 at 02:09 UTC ( [id://1009266]=perlquestion: print w/replies, xml ) Need Help??

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

#!/usr/local/bin/perl5.8 -w use strict; print "Currency Converter\n\nPlease enter the ex rate: "; my $yen = <STDIN>; print "\nEnter a price to convert: "; my $price = <STDIN>; print "$price Yens ", ($price/$yen), " pounds\n";
##Why does my last print link, print the output and then again the output

Replies are listed 'Best First'.
Re: Question why my code is posting a new line
by Athanasius (Archbishop) on Dec 18, 2012 at 02:35 UTC

    Hello chiggly007, and welcome to the Monastery!

    When the user types (say) “1.5” and presses “Enter”, $price is assigned “1.5\n” (note the newline). Then when print "$price" is called, this newline is printed to the screen.

    Solution: chomp the input:

    my $price = <STDIN>; chomp $price; print "$price Yens ", ($price / $yen), " pounds\n";

    (Also, please fix the <code> / </code> tags in your post so that your script prints clearly. See Markup in the Monastery.)

    Hope that helps,

    Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

      Thanks for the help Athanasius. So are you saying that assigning a variable, and hitting Enter , Perl automatically assigns a "\n" to that variable? Thanks

        No. Athanasius is implying that:

        my $price = <STDIN>;

        reads an entire line including the end of line character(s) into $price. Perl doesn't "add" the new line, it was there in the input. chomp may be used to remove a trailing line end.

        Most often the line end is represented in Perl strings as \n regardless of operating system. In various cases is can be other strings (for example when the content of $/ has been changed).

        True laziness is hard work

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others chilling in the Monastery: (9)
As of 2024-04-23 10:33 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found