in reply to Re: Re: Dynamically allocating variables
in thread Dynamically allocating variables
Here is an example that reads 'configuration info' from Perl's built in DATA filehandle. I use DATA because it's easy and you only need one file for demonstrations. Anyhow, the configuration is simply two values seperated by a comma per line. The while loop processes DATA one line at a time and creates a new struct object with the values it finds. After the struct is instantiated, it is pushed to an array. Since it is already a reference there is no need to de-reference it. The last line is a for loop that prints out only one of the attributes for each struct in the array.
But hold it right there! Why are you using Class:Struct? No offense to the author, but if you are going to code in Perl, code like Perl. Check this out:use strict; use Class::Struct; # declare the struct struct(MyStruct => { even => '$', odd => '$', }); # create array of structs my @structs; while (my $line = <DATA>) { chomp $line; my ($odd,$even) = split(',',$line); my $obj = new MyStruct; $obj->odd($odd); $obj->even($even); push(@structs,$obj); } print $_->odd(), "\n" foreach (@structs); __DATA__ one,two three,four five,six seven,eight nine,ten
Same thing with less lines, and i spared using map to golf it down even further ... oh what the hell:use strict; # create array of structs my @structs; while (my $line = <DATA>) { chomp $line; my ($odd,$even) = split(',',$line); my %hash = ( odd => $odd, even => $even, ); # i do have to de-reference %hash though push(@structs,\%hash); } print $_->{'odd'}, "\n" foreach (@structs); __DATA__ one,two three,four five,six seven,eight nine,ten
Welcome to Perl. :)print $_->{odd},"\n"for map{my($o,$e)=split',',$_;{odd=>$o,even=>$e}}< +DATA>;
jeffa
L-LL-L--L-LL-L--L-LL-L--
-R--R-RR-R--R-RR-R--R-RR
F--F--F--F--F--F--F--F--
(the triplet paradiddle)
|
|---|