sandra_henrystocker
Unix Dweeb

Combining arguments in a perl script

How-To
Jul 9, 20152 mins

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 

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.

sandra_henrystocker

Sandra Henry-Stocker was a programmer, Linux systems administrator, security engineer and Linux journalist for most of her 30-year career. She describes herself as "USL" (Unix as a second language) but remembers enough English to write books and buy groceries. She lives in the mountains in Virginia where, when not working with or writing about Unix, she's chasing the bears away from her bird feeders. Tune into her 2-Minute Linux video tutorials and take command of your command line.

More from this author