PERL How To Print A List Without A Loop

PERL has a built-in function called join() that will concatenate a list with a given string. The official perldoc states:

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);

From the code example, you can make CSV output and all kinds of goodies, but what the doc misses and the example doesn’t show is that combining join() with a print statement makes writing lists to STDOUT or a file handle a snap. This is where join() really shines.

Example:

Code
@names = ('Mark', 'Jim', 'Bob','Mary','Steven','Gomer');
print join("\n", @names);

Output
Mark
Jim
Bob
Mary
Steven
Gomer

Note that this will NOT print a final or beginning string. Join() concatenates the elements, meaning it puts the string value BETWEEN the list elements.

Did you find this post useful or have questions or comments? Please let me know!

This entry was posted in How Tos, perl, Programming, Software. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *