View Full Version : Explanation of Code

06-20-2009, 03:07 AM
I'm new to coding so I apologize in advance if my questions are basic.

I wrote this basic piece of code but frankly I don't understand what is actually happening

#(Script 1)

print "What is your name?\n";
chomp($name = <STDIN>); #waits for user input from keyboard
print ("$name" & 'name');

Here's the executed code

Process started >>>
John Doe
What is your name?
Jahd<<< Process finished.

I'm trying to learn by experimentation and I was wondering if anyone could explain why the output is Jahd. What exactly is the computer doing?

06-20-2009, 05:29 AM
print ("$name" & 'name');

Jahd<<< Process finished.

What exactly is the computer doing?

It's only doing what you asked it to do. Ever heard of "garbage in - garbage out"? :D

By using the ampersand in the print function, you're telling it to print the "bitwise AND (http://en.wikipedia.org/wiki/Bitwise_operation)" of the input string and the string 'name'. As I understand it, when applied to strings, it operates on the character codes.

06-20-2009, 07:11 PM
this line:

print ("$name" & 'name');

is the same as:

print $name & 'name';

your use of parenthesis and quotes is just confusing the issue to you. As already pointed out, & is a perl operator. If you wanted to print a string you should have done this:

print "$name & 'name'";

If thats not what you wanted to do then you have to let us know what your intention was.

06-21-2009, 02:09 AM
Thank you for both of your replies, it clears up my question.

To KevinADC
I'm trying to learn by experimentation and errors. Most of the time I can see where I made a mistake and how it affected the output but in this case I had no idea what was happening. But now I know it's a bitwise operation
Thank you so much for the explanations