Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

some questions on a perl program

Tags:

perl

With respect to the following code segment, I would like to know whether my understanding on several issues are correct?

1) In the structure of $model->{in1}->{tra1}->{data}} , “in1”, “tra1”, and “data” all represent specific keys at different levels of hash structures.

2) Does $#{$model->{in1}->{tra1}->{data}}represent an array?

3) What does my @cus = sort keys %cus; aim to do? Are the “cus” at the right side and the “cus” at the left side the same thing?

my %cus = ();
for my $i ( 0 .. $#{$model->{in1}->{tra1}->{data}})
{
  foreach  my $cu (keys %{$model->{in1}->{tra1}->{data}->[$i]->{concept}}
   {
       $cus{$cu} = 1;
   }
 }
my  @cus = sort keys %cus;
like image 254
user785099 Avatar asked May 18 '26 21:05

user785099


1 Answers

1)

They are keys to different hashes, yes.

  • in1 is used as the key to the hash referenced by $model.
  • tra1 is used as the key to the hash referenced by $model->{in1}.
  • data is used as the key to the hash referenced by $model->{in1}->{tra1}.

2)

  • $#a returns the last index of array @a.

so

  • $#{ $ref } (or $#$ref for short) returns the last index of @{ $ref } (or @$ref for short), the array referenced by $ref.

so

  • $#{ $model->{in1}->{tra1}->{data} } returns the last index of @{ $model->{in1}->{tra1}->{data} }, the array referenced by $model->{in1}->{tra1}->{data}.

3)

The statement sorts the keys of the hash %cus and places them in array @cus. No, %cus and @cus aren't the same variable.

"4")

The code can be simplified to:

my %cus;
my $data = $model->{in1}->{tra1}->{data};
for my $i (0 .. $#$data) {
   for my $cu (keys %{ $data->[$i]->{concept} }) {
      ++$cus{$cu};
   }
}

my @cus = sort keys %cus;

Or even:

my %cus;
for my $data_item (@{ $model->{in1}->{tra1}->{data} }) {
   for my $cu (keys %{ $data_item->{concept} }) {
      ++$cus{$cu};
   }
}

my @cus = sort keys %cus;
like image 186
ikegami Avatar answered May 21 '26 13:05

ikegami



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!