I am new to Perl. I want to concatenate a string and a number with the .
operator and the first argument will be a number. I can use join, sprintf and simply print them as print number,string. But I tried it with the .
operator and got the following:
$foo = "hello".34 # Gives hello.34
$foo = 34."hello" # Gives an error
$foo = 34.34 # Gives 34.34
$foo = 34.34.34 # Gives """
$foo = "hello".34."hello" # Gives an error
I tried them under Perl debugger.
Why doesn't Perl concatenate a number and string with number as first argument while vice versa works fine? Why does 34.34.34 give """ in Perl?
Every now and then, whitespace is significant. 34 . "hello"
is "34hello"
. 34."hello"
is a parse error because 34.
looks like the beginning of a floating-point number (maybe 34.5
), and then the parser doesn't know what to do when it gets a "
instead of another digit. Your code will look better anyway if you use spaces around the dot operator, but following a number it's required.
34.34.34
is a special construct called a version string or "v-string" that occurs when you have a number with multiple dots in it, optionally preceded by a v
. It creates a string where each character number comes from the numbers in the v-string. So 34.34.34
is equal to chr(34) . chr(34) . chr(34)
, and since chr(34)
is a double-quote, that's the same as '"""'
. V-strings are useful because they compare the way that version numbers are expected to. Numerically, 5.10 < 5.9
, but as versions, 5.10.0 gt 5.9.0
.
Excellent question. The .
character has multiple meanings:
It's the concatenation operator
my $x = 34;
my $y = 34;
say $x.$y; # 3434
It's the decimal separator in floating-point numeric literals:
3434 / 100 == 34.34
Note that the decimal separator must immediately follow the integral part, or it's interpreted as concatenation: 34 .34 == 3434
It's the separator in v-strings (where “v” usually stands for version). In a v-string, each character is separated by a period, and is optionally prefixed by a v
:
34.34.34 eq v34.34.34
Each number is translated to the corresponding character, e.g. 64.64.64 eq "@@@"
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With