Printing strings

W

worlman385

why the follow print statement only print the number$C

$C = 15;

print "Number of C is " + $C +"\n";
 
J

Jürgen Exner

why the follow print statement only print the number$C

$C = 15;

print "Number of C is " + $C +"\n";

What do you expect to be printed if not the value of $C?
The numerical value of the other two summands in your addition are both 0,
so 0 + 15 + 0 should result in 15, shouldn't it?

jue
 
S

Sherm Pendley

why the follow print statement only print the number$C

$C = 15;

print "Number of C is " + $C +"\n";

You're using numerical addition. The numeric values of the two strings
are 0, so essentially what you're doing above is:

print 0 + $C + 0;

If you want to concatenate strings, you have to use the right operator
for that - this isn't C++ or Java, where the "+" operator is overloaded
to do everything except make coffee. :)

The string concatenation operator is "." (without the quotes), so what
you wanted to do is:

print "Number of C is " . $C . "\n";

Another way to do that is what Perl calls "interpolation". When you use
a double-quoted string, you can use variables directly in the string:

print "Number of C is $C\n";

Compare this with the output from single-quoted form, which doesn't do
the interpolation:

print 'Number of C is $C\n';

And finally, concatenating a bunch of strings together just to print the
result isn't the most efficient way to do it. You can also pass a series
of arguments to print(), which will print them one after another:

print "Number of C is", $C, "\n";

To be honest though, you'd have to print a few million strings to notice
the difference in most circumstances.

For details, have a look at:

perldoc perlop

sherm--
 
A

anno4000

Sherm Pendley said:
why the follow print statement only print the number$C

$C = 15;

print "Number of C is " + $C +"\n";
[...]

The string concatenation operator is "." (without the quotes), so what
you wanted to do is:

print "Number of C is " . $C . "\n";
[...]

And finally, concatenating a bunch of strings together just to print the
result isn't the most efficient way to do it. You can also pass a series
of arguments to print(), which will print them one after another:

print "Number of C is", $C, "\n";
^^
You want a blank there.
To be honest though, you'd have to print a few million strings to notice
the difference in most circumstances.

In my view it isn't efficiency so much as the principle to use the
simplest possible tool. Since print() has concatenation built in,
using the dot operator falls clearly in that category.

Anno
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top