It would be helpful if you could explain more about what end objective or application you are trying to achieve. While what you are asking about is indeed possible, there may be some other Perl data structure that is better suited for your goal. One possibility is a hash table as I show below. There are other possibilities. To make a specific recommendation, I'd have to have more information.
Update: I updated the code to show more possibilities. Perl has all sorts of cool ways to build what would be complicated to construct structures in C or other languages fairly easily. Once I was able to translate your input string into pairs, it was easy to make several different data structures to represent that data. Perl has massive power to take a lot of the "grunt work" out of doing this stuff and you can get a lot of help here. The Perl syntax does require some learning, but there are good tutorials. If you look at what I called "the second 2-D way", this is really neat because you don't wind up with "column names" to "column number" translations, you can just say, "hey, for row 2, give me the "name" and the "animal" in a very straightforward way.
I think you are posing what in this forum's lingo is an XY problem. You are asking about X but what you really need is Y.
#!/usr/bin/perl -w
use strict;
my $string = 'Tom.Dog.Ben.Cat.Howie.Dog.Trigger.Horse';
my @pairs = split(/\./,$string);
my %petNames; #one way with a hash table
my @twoD_array_simple; #a simple 2D array
my @twoD_array; #Another "2-D" way
while (@pairs)
{
my ($name, $animal) = splice(@pairs,0,2);
push (@{$petNames{$animal}}, $name); #one way with a hash table
push (@twoD_array_simple, [$name, $animal]); #a simple 2D array
push (@twoD_array,
{name => $name, animal => $animal}); #Another "2-D" way
}
print "A hash table to combine names for each animal:\n";
foreach my $animal (keys %petNames)
{
print "$animal => @{$petNames{$animal}}\n";
}
print "\nA simple 2-Dimensional array representation:\n";
foreach my $aref (@twoD_array_simple)
{
print "@$aref\n";
}
print "\nOne item of simple 2-D array (3rd row, second column):\n";
print "$twoD_array_simple[2][1] ... that's Howie's animal\n";
print "\nAnother 2-D way without using indices for the columns:\n";
foreach my $href (@twoD_array)
{
print "$href->{name} is a $href->{animal}\n";
}
print "\nOutput one row using the \"another 2-D way\"\n";
print "$twoD_array[2]->{name} $twoD_array[2]->{animal}".
" ....that is the third row\n";
__END__
PRINTS:
A hash table to combine names for each animal:
Horse => Trigger
Cat => Ben
Dog => Tom Howie
A simple 2-Dimensional array representation:
Tom Dog
Ben Cat
Howie Dog
Trigger Horse
One item of simple 2-D array (3rd row, second column):
Dog ... that's Howie's animal
Another 2-D way without using indices for the columns:
Tom is a Dog
Ben is a Cat
Howie is a Dog
Trigger is a Horse
Output one row using the "another 2-D way"
Howie Dog ....that is the third row
|