Lotus1 has asked for the wisdom of the Perl Monks concerning the following question:
A new teammate demonstrated something like the following at the beginning of a script.
use strict; use warnings; our @arr = <ABC DEF GHI>;
I'm going to go over when to use our but I'm struggling with what to say about using glob like this. It works as long as there isn't a metacharacter other than curly braces. He has been told already about the use of qw() to create an array like this but I suspect he copied this from somewhere. In the perldocs for glob I found this:
If non-empty braces are the only wildcard characters used in the glob, no filenames are matched, but potentially many strings are returned. For example, this produces nine strings, one for each pairing of fruits and colors:1. my @many = glob "{apple,tomato,cherry}={green,yellow,red}";
I created the following to try to show why it's a bad idea.
use strict; use warnings; use Data::Dumper; my @arr1 = < abc def ghi f* >; my @arr2 = qw( abc def ghi f* ); my @arr3 = glob('abc def ghi z*'); print Dumper(\@arr1); print Dumper(\@arr2); print Dumper(\@arr3); __DATA__ $VAR1 = [ 'abc', 'def', 'ghi', 'file1.txt', 'file2.txt' ]; $VAR1 = [ 'abc', 'def', 'ghi', 'f*' ]; $VAR1 = [ 'abc', 'def', 'ghi' ];
perl -MO=Deparse glob_to_array.pl produces the following.
use Data::Dumper; use File::Glob (); use warnings; use strict 'refs'; my(@arr1) = glob(' abc def ghi f* '); my(@arr2) = ('abc', 'def', 'ghi', 'f*'); my(@arr3) = glob('abc def ghi z*'); print Dumper(\@arr1); print Dumper(\@arr2); print Dumper(\@arr3); glob_to_array.pl syntax OK
Deparse shows that qw() does the job without calling glob and risking something unexpected if the text happens to contain a metacharacter (other than curly braces). The best thing I can come up with is for a program that the team will need to support this is a bad idea since it could cause unintended and confusing side effects. Suggestions for better demonstrations or documentation would be appreciated. Maybe I'm being too critical and should lower my critic setting.
Note: I changed the title
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Creating arrays with glob patterns without metacharacters
by haukex (Archbishop) on Jan 05, 2018 at 16:41 UTC | |
by Lotus1 (Vicar) on Jan 05, 2018 at 17:09 UTC | |
Re: Why are glob patterns without metacharacters returned
by Eily (Monsignor) on Jan 05, 2018 at 16:14 UTC | |
by Lotus1 (Vicar) on Jan 05, 2018 at 16:21 UTC | |
by Eily (Monsignor) on Jan 05, 2018 at 16:24 UTC |