December 23, 2010
Perl Struct Example
Problem
Provide example code in Perl to implement an array of C like structs
Solution
Use a hash table. The hash key is recommended to be a unique identifier and the hash value is a reference to an array. The idea is simple and the rest is just using the correct Perl syntax
Code
Here is how to do that in Perl
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
#!/usr/bin/perl # Define a hash table to store all structs my %structs = (); # Each hash entry represents a particular struct # The hash keys are 1, 2, 3, ... and the actual struct # values are stored in an array which is the hash # value $structs{"1"} = ["CA", "San Jose", "Fox Chase"]; $structs{"2"} = ["CA", "Santa Clara", "First Street"]; $structs{"3"} = ["CA", "Sunnyvale", "El Camino Real"]; # For each struct key in the hash do foreach $key (sort keys %structs) { # Print struct key print $key . " "; # Each struct is an array that is why we use the @ # symbol and $structs{$key} is the array reference # which is nothing but the hash value for a particular # $key foreach $struct (@{$structs{$key}}) { # Print struct data members print $struct . " "; } print "\n"; } |