Combining arguments in a perl script

gluegun
Credit: Sandra H-S

Here's a trick that I learned recently that allows me to combine a string of arguments into a single variable. In my case, this was necessitated by a script that I was preparing to help analyze Windows file shares. In case you haven't noticed, those Windows folks are still creating directories with blanks in their names. Sigh! I didn't want to have to concern myself with putting quotes around the names of the shares that I was analyzing so that I could supply them as arguments.

The trick is to to use the join command as shown in the example below. This command joins pieces of text separated by blanks into a single $sharename variable. So now I can put the names of all the shares that I want to evaluate in a file, without worrying that some might contain blanks, and process them as a group.

if ( $#ARGV < 0 ) {
    print "USAGE: perl -w $0 sharename\n";
    exit 1;
} else {
    $sharename=join(" ", @ARGV);	# <== join
    print "working with $sharename\n";
}

The join function does the reverse of the split command. Where split takes a string and breaks it into pieces based on the character of your choosing, join pulls them back together. You might, for example, want to take a series of variables and pull them into a single string.

$string = join ( ':', $lastname, $firstname, $ID, $city, $state );

This will set the value of $string to something like "Doe:John:1234:Strasburg:VA". Doing the same thing with the . operator would be quite a bit messier:

$string = $lastname . ":" . $firstname . ":" . $ID . ":" . $city . ":" . %state;

You can use the join command to make a string out of the elements in any arbitrary array. The @ARGV reference is, after all, the array that contains the arguments passed to the script. If you prefer to not insert a separator between the array elements when they're combined into a string, use a null string as shown below.

$string = join ( '', @array );

Both uses of the join command can be useful, especially when you need to insert delimiters between your pieces of text.

This article is published as part of the IDG Contributor Network. Want to Join?

To express your thoughts on Computerworld content, visit Computerworld's Facebook page, LinkedIn page and Twitter stream.
Related:
Windows 10 annoyances and solutions
Shop Tech Products at Amazon
Notice to our Readers
We're now using social media to take your comments and feedback. Learn more about this here.