Lady_Aleena has asked for the wisdom of the Perl Monks concerning the following question:
Several weeks ago I was playing around with glob's ability to create lists from stringified lists. (The forth paragraph in the doc.) I at first wanted to see if I could feed it arrays directly, but I was shown by jeffa the lists had to be comma separated strings. After playing around with it for a few minutes, I thought about finding a way use arrays, so wrote the following.
Note: I do not like the name of the subroutine, so I am open to suggestions.
sub glob_array { my (%opt) = @_; my $joiner = $opt{'joiner'} ? $opt{'joiner'} eq ' ' ? "' '" : $opt{ +'joiner'} : ''; my $space = $opt{'space holder'} ? $opt{'space holder'} : '_'; # The arrays have to be strinified into comma separated lists. Thank + you to jeffa for showing me. my $arrays = [map { $_ = '{'.join( ',', @{$_} ).'}'; $_ =~ s/ /$spac +e/g; $_; } @{$opt{'arrays'}}]; my $string = join( $joiner, @$arrays ); my @raw_array = glob "$string"; my @array = map { $_ =~ s/$space/ /g; $_; } @raw_array; return \@array; }
Here are some sample arrays and how they would look once glob has done its work.
my @colors = qw(red green blue); my @directions = qw(north south east west); my @numbers = (1..3); my $array = glob_array( 'arrays' => [\@colors, \@directions, \@numbers +], 'joiner' => ' ', 'space holder' => '__' );
Output
$VAR1 = [ 'red north 1', 'red north 2', 'red north 3', 'red south 1', 'red south 2', 'red south 3', 'red east 1', 'red east 2', 'red east 3', 'red west 1', 'red west 2', 'red west 3', 'green north 1', 'green north 2', 'green north 3', 'green south 1', 'green south 2', 'green south 3', 'green east 1', 'green east 2', 'green east 3', 'green west 1', 'green west 2', 'green west 3', 'blue north 1', 'blue north 2', 'blue north 3', 'blue south 1', 'blue south 2', 'blue south 3', 'blue east 1', 'blue east 2', 'blue east 3', 'blue west 1', 'blue west 2', 'blue west 3' ];
I have yet to figure out how to make this more interesting by including a pattern or a single joiner. From the above output, instead of plain green west 2 having green sector west tower 2nd floor or something akin to it. I could pre-munge the lists, but adding the ability to use a pattern would be nice too.
So, I would like a new name for the subroutine and maybe some pointers on how to add in a pattern to this. Also, maybe a few good reasons to use this I may not be seeing other than making a list to use for random selection.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: RFC: Playing with glob
by MidLifeXis (Monsignor) on Sep 15, 2015 at 20:14 UTC | |
by stevieb (Canon) on Sep 15, 2015 at 20:26 UTC | |
|
Re: RFC: Playing with glob
by jeffa (Bishop) on Sep 15, 2015 at 22:48 UTC | |
by Lady_Aleena (Priest) on Sep 16, 2015 at 19:19 UTC | |
|
Re: RFC: Playing with glob
by Anonymous Monk on Sep 15, 2015 at 23:21 UTC |