Home: Perl Programming Help: Beginner:
printing a variable goes to next line



jazzo
Novice

Aug 6, 2012, 9:58 AM


Views: 1955
printing a variable goes to next line

Hi there, I wonder if you can help me with this. Here's my script:

Code
#!/usr/bin/perl 
#money_user_input.plx
use strict;
use warnings;
print "Enter a value here\n";
my $money = <STDIN>;
print "I have $money in my account\n";

Whenever I run this script in the terminal I have this output:

antobbo@antobbo-xps17-ubuntu:~/begperl$ perl money_user_input.plx
Enter a value here
3466
I have 3466
in my account

Now why does "in my account" go onto the following line? I didn't include any

Code
\n

, just at the end. What is it that I am doing wrong please?
thanks


Laurent_R
Veteran / Moderator

Aug 6, 2012, 10:39 AM


Views: 1954
Re: [jazzo] printing a variable goes to next line

Do this:


Code
my $money = <STDIN>;  
chomp $money;
print "I have $money in my account\n";


The chomp function will remove the carriage return that you inserted at the end of the $money variable when you hit enter the value.


jazzo
Novice

Aug 6, 2012, 11:01 AM


Views: 1953
Re: [Laurent_R] printing a variable goes to next line

fantastic thanks, it works.
One question though: if chomp is a function shouldn't the variable be a parameter of the function like

Code
chomp ($money);

?
thanks


Laurent_R
Veteran / Moderator

Aug 6, 2012, 1:59 PM


Views: 1941
Re: [jazzo] printing a variable goes to next line

If you write:


Code
chomp $money;


you are really saying that $money is the parameter to the chomp fonction.

You can put it in parens, but this is not required.


jazzo
Novice

Aug 6, 2012, 2:25 PM


Views: 1938
Re: [Laurent_R] printing a variable goes to next line

ok fantastic, thanks, it's that I wasn't sure what was the right syntax, I just want to make sure I learn the basics correctly. In javascript and I remember when I looked into c++ all the functions have brackets () so I assume I had to use them here too. I haven't got yet to functions in perl, so hopefully the brackets usage will become clear then
thanks


Laurent_R
Veteran / Moderator

Aug 6, 2012, 11:12 PM


Views: 1925
Re: [jazzo] printing a variable goes to next line

In Perl, most internal functions don't require parentheses. But you can put some if you wish or if you want to get the right precedence.

you can say:

print reverse sort keys %hash;

or

print (reverse (sort ( keys (%hash))));


jazzo
Novice

Aug 7, 2012, 10:47 AM


Views: 1918
Re: [Laurent_R] printing a variable goes to next line

fantastic thanks