Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Number and string concatenation in Perl

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?

like image 920
xtreak Avatar asked Feb 22 '14 19:02

xtreak


Video Answer


2 Answers

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.

like image 110
hobbs Avatar answered Sep 21 '22 20:09

hobbs


Excellent question. The . character has multiple meanings:

  1. It's the concatenation operator

    my $x = 34;
    my $y = 34;
    say $x.$y; # 3434
    
  2. 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

  3. 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 "@@@".

like image 34
amon Avatar answered Sep 23 '22 20:09

amon