Reputation: 149
I'm watching a training video of UDEMY for perl, but the video is not clear and looks like it contains errors.
The training is showing how to concatenate 2 strings with the following example:
#!usr/bin/perl
print $str = "Hi";
print $str .= " there\n";
However when I run the script it the output is: HiHi There
Where is the second Hi coming from? Am I missing something?
Upvotes: 2
Views: 170
Reputation: 107899
If the training really shows this script, ditch it — it's not code that one would normally write.
$str = "Hi"
sets the variable $str
to the string "Hi"
. Most of the time, the value of an assignment is not used, the assignment is only performed for its side effect which is to change the value of the variable. However, in Perl, an assignment does have a value, which is the value that is assigned to the variable. The instruction print $str = "Hi"
prints the value that is assigned, i.e. this prints the string "Hi"
.
The second instructions assigns to $str
the value that consists of the old value of $str
concatenated with " there\n"
, i.e. $str
is set to "Hi there\n"
. Once again, the value that is assigned is printed, i.e. this prints the string "Hi there\n"
.
Normally one would not use the value of the assignments:
#!/usr/bin/env perl
my $str = "Hi";
$str .= " there\n";
print $str;
Upvotes: 7
Reputation: 727
The first statement assigns the value "Hi" to $str, then prints it. The second statements adds the value " there\n" to $str, making the $str equal to "Hi there\n", then prints it. Thus, the output you're getting is correct for what you're telling the interpreter to do.
Upvotes: 8