By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
438,177 Members | 976 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 438,177 IT Pros & Developers. It's quick & easy.

How to traverse through a array reference

P: 1
Hi

I am having problems going through the hash reference and outputting the result.

Can someone tell me how to traverse thorugh the output of "p4 info" using Perl.
p4 info is a command in perforce.

Is there any way I can increment an address and look what is stored inside till I hit EOF just like C . The reason is that this array could be an array of hashes or array of arrays or any mixed combination.

Any help is greatly appreciated ?

Expand|Select|Wrap|Line Numbers
  1. sub run_info()
  2.   {
  3.      my $key;
  4.      my $value;
  5.      my $p4_info;
  6.      my $val;
  7.      $p4_info = $p4->Run( "info" );
  8.  
  9. ## p4_info is a reference to an array but I dont know what is inside that array.
  10. ##    p4_info is ARRAY(0x226f8c) 
  11.  
  12.      print ("\n p4_info is $p4_info \n");
  13.     #my $ref = \@p4_info;
  14.     foreach  $key ( sort keys %{$p4_info})
  15.    {
  16.   print( $key, "->  \n" );
  17.          #print @{$p4_info->{"clientAddress"};
  18.         }
  19.   }
Thanks
Sunny
Jan 5 '09 #1
Share this Question
Share on Google+
2 Replies


KevinADC
Expert 2.5K+
P: 4,059
if $p4_info is an array:

Expand|Select|Wrap|Line Numbers
  1. foreach my $line (@{$p4_info}) {
  2.    print "$line\n";
  3. }
if $p4_info is a hash:

Expand|Select|Wrap|Line Numbers
  1. foreach my $key (keys %{$p4_info}) {
  2.    print "$key = $pf_info->{$key}\n";
  3. }
if you need to check what type of a reference something is use the ref() function. A simple example:

Expand|Select|Wrap|Line Numbers
  1. my $ref = ref($p4_info);
  2. if ($ref eq 'ARRAY') {
  3.     its an array
  4. }
  5. elsif ($ref eq 'HASH') {
  6.    its a hash
  7. }
  8. else {
  9.    its something else
Jan 6 '09 #2

eWish
Expert 100+
P: 971
If you want to see what is inside an array or hash you can use Data::Dumper

If you want to loop through an array reference you can use the following.

Expand|Select|Wrap|Line Numbers
  1. my @my_array = qw/1 2 3 4 5 6 7 8 9 10/;
  2.  
  3. my $array_ref = \@my_array;
  4.  
  5. #Data::Dumper apporach
  6. print Dumper(\$array_ref), "\n";
  7.  
  8. #Print each elemnt of the array reference joined with a newline
  9. print join "\n", @{$array_ref};
  10.  
  11. #Loop through each element of the array reference
  12. for (@{$array_ref}) {
  13.     print $_, "\n";
  14. }
--Kevin
Jan 6 '09 #3

Post your reply

Sign in to post your reply or Sign up for a free account.