Function join() in Perl

In the Perl programming language has a built-in function join(). Using this function, you can combine multiple values in a string.

Here's an example:

▶ Run
#!/usr/bin/perl

my $str = join('<>', 'a', 'b', 'c');
print $str;

The program will display the text a<>b<>c.

Arguments

my $str1 = join($separator, $value1, $value2);
my $str2 = join($separator, @arr);
my $str3 = join($separator, @arr1, @arr2);

Standard using join() is to give her two or more arguments. The first value which is passed to the function is the string to split. Function join() returns a string in which all values starting with a second connected together, and between them is a separator. Example (program will a:b:c:d):

▶ Run
#!/usr/bin/perl

print join(':', 'a', 'b', 'c', 'd');

In the event that after the value separator is only one value then the result is a string which consists only of the second value. Example (the program will display a):

▶ Run
#!/usr/bin/perl

print join(':', 'a');

The value split may be one or more characters and may be empty line ''. If you use an empty string as the first value, the result of the function is the concatenation of values. Example (the result of program ABC):

▶ Run
#!/usr/bin/perl

print join('', 'A', 'B', 'C');

If the functions join() does not pass any arguments, it will error:

Not enough arguments for join or string at script.pl line 3, near "join()"
Execution of script.pl aborted due to compilation errors.

If the transfer function join() single argument, the result will be always an empty string ''. If you pass undef as the only argument, then the result will be an empty string, but included use warnings, on STDERR you will receive a warning:

Use of uninitialized value in join or string at script.pl line 5.

Return value

The result of the function join() is always a string.

Even if you use join() with numbers, the result is still a string, not a number. If you write join(1, 22, 33), the result will be a string '22133', not the number 22133. But it's hard to imagine a situation in which you had to join() returns the amount not a string. But in the case of Perl it is possible to use strings in all math operations. Read more about how Perl converts strings to numbers.

Related topics

Official documentation

Here is the output of the command perldoc -f join:

       join EXPR,LIST
               Joins the separate strings of LIST into a single string with
               fields separated by the value of EXPR, and returns that new
               string.  Example:

                   $rec = join(':', $login,$passwd,$uid,$gid,$gcos,$home,$shell);

               Beware that unlike "split", "join" doesn't take a pattern as
               its first argument.  Compare "split".

Other articles

Comments