How can I substitute an array for macro like keyword in Perl?
I am defining a lot of arrays of structs in a module. e.g.
my $array = [
{
Field1 => "FieldValue1"
},
{
#etc...
},
];
my $array2 = [
{
Field1 => "FieldValue1"
},
{
#etc...
},
];
I often repeat sequences of st开发者_StackOverflow社区ructs. For instance I might have five { Field1 => "FieldValue1" } structs in a row. Is it possible to save the sequence of structs in some data structure and insert that into my arrays?
e.g.
my $array3 = [ $Field1, $Field1, $Field1 ]; # $Field1 is a sequence of structs
You can do that but they will all wind up copies of each other. So editing the first one will change all of them. Instead use map
.
my $array3 = [ map {Field1 => "FieldValue1"}, 1..5 ];
Any time that you find yourself repeating boilerplate code, Perl usually has a way around it.
I am not entirely clear what you want to do, but you could do something like this:
sub make_struct {
{Field1 => "FieldValue1"}
}
my $array = [map make_struct, 1 .. 10]; # array with 10 hashes
sub make_struct_array {[map make_struct, 1 .. $_[0]]}
my $array2 = make_struct_array 20; # array with 20 hashes
So in other words, write a subroutine that returns a new data structure for you. The subroutine can take a variety of options if you need to customize the structure.
The answers above work well for their own purposes, but they were not exactly what I wanted.
I ended up usin push()
to create the arrays. $templatearray1
and $templatearray2
are arrays of structs. Push()'s behavior is to not insert the array reference. Instead it inserts the elements of the arrays.
e.g.
my $myarray = [];
push(@$myarray, @$templatearray1);
push(@$myarray, @$templatearray2);
push(@$myarray, @$templatearray1);
push(@$myarray, @$templatearray2);
push(@$myarray, @$templatearray1);
push(@$myarray, @$templatearray2);
push(@$myarray, (
{
key1 => 'blah1',
key2 => 'blah2',
},
));
精彩评论