eWebProgrammer eweb  






Perl Variables  «Prev  Next»
Lesson 11 Join Function in Perl
Objective Perl Join Function to format arrays
The join and split functions are tremendously useful for working with arrays.
You will find that you use these two functions quite often as a convenient method of formatting arrays for both display and storage.
In this lesson, we will examine the use of join, and in the next we will look at the use of split.
We have already used the join function in the array examples in the previous lessons, but here I will give you a more formal definition of the syntactical structure:
join separator, LIST
The separator is any scalar, and the LIST is any list of scalars (including an array).
A common use of this function is to print a comma-separated list of an array:
@array = ("Black", "Brown", "Polar", "Grizzly");
print join(', ', @array), "\n";
When run, you will get this output:
Black, Brown, Polar, Grizzly

Function Calls in Perl
Even though the parenthesis are not required for built-in functions in Perl, it's a good idea to use them when the function call is not the only element in the statement.
Otherwise (due to the different leftward and rightward precedence) you may not always get the result you want.
For example, if you remove the parenthesis from the join in the above code, the "\n" becomes part of the list being passed to join, so you will get this output instead:
Black, Brown, Polar, Grizzly
Another common usage for join is to delimit an array for storage in a flat file. Later the delimited data can be read back into an array with split. Here's an example:
@array = ("Black", "Brown", "Polar", "Grizzly");
print join(':', @array), "\n";
That prints the array with colons separating the elements like this:
Black: Brown: Polar: Grizzly 
To put them back into an array, you can use the split function.