open (FILE, "/somepath/temp.txt"); $inp_counter = 0; $var_counter = 0; while () { if ( /^Page.\s*=\s*(.*)/ ){ push @input_page_array, $1; $inp_counter = @input_page_array; } elsif ( /^Start*/../^End*/) { $line=$_; if ($line=~/^\s*(\w+)\s=\s(.*)/ ){ if ($1 eq "varname") { # if varname is found, and if it is not the first time, then push the hash into an array if ($var_counter != 0) { push @AoH, {%h}; } $var_counter++; %h = &initialize_struct( $1, $2, $inp_counter) } else { createpair( $1, $2); } } } } # push the final pair into the array push @AoH, {%h}; # get the elements in the array that correspond to the pagenum.. in this case, i am getting all elements for page 2 for $i ( 0 .. $#AoH ) { for $role (sort( keys %{ $AoH[$i] } )) { if ($role eq "pagenum" && $AoH[$i]{"pagenum"} == 2) { push @required, $i; } } } #print the elements for the selected page foreach $ii (@required) { for $role1 (sort( keys %{ $AoH[$ii] } )) { print "$role1=$AoH[$ii]{$role1}\n"; } print "\n\n"; } # subroutine to initialize the structure and add 'pagenum' and 'varname' sub initialize_struct() { my ( $key, $value, $inp_cnt) = @_; my %hh; %hh = ( pagenum => "", varvame => "", varval => "", etc... , etc... ); $hh{$key} = $value; $hh{'pagenum'} = $inp_cnt; return %hh; }; # subroutine to populate rest of the data structure sub createpair{ my($key, $value) = @_; $h{$key} = $value; };