开发者

What does {$histogram{$value}++} mean in Perl?

开发者 https://www.devze.com 2022-12-21 07:59 出处:网络
The whole subroutine for the code in the title is: sub histogram { # Counts of elements in an array my %histogram = () ;

The whole subroutine for the code in the title is:

sub histogram { # Counts of elements in an array
  my %histogram = () ;
  foreach my $value (@_) {$histogram{$value}++}
  return (%histogram) ;
}

I'm trying to translate a Perl script to PHP and I'm having difficulties with it (I reall开发者_JAVA技巧y don't know anything of Perl but I'm trying).

So how do I put this {$histogram{$value}++} into PHP?

Thanks!


{$histogram{$value}++} defines a block and in Perl the last line of a block doesn't need a terminating semicolon, so it is equivalent to {$histogram{$value}++;}.

Now the equivalent of hash in PHP is an associative array and we use [] to access the elements in that array:

$hash{$key} = $value;      // Perl
$ass_array[$key] = $value; // PHP

The equivalent function in PHP would be something like:

function histogram($array) {
    $histogram = array();
    foreach($array as $value) {
        $histogram[$value]++;   
    }
    return $histogram;
}


<?php
  $histogram = array_count_values($array);
?>


foreach my $value (@_) {$histogram{$value}++}

It is a single line variant of:

foreach my $value (@_) {
    $histogram{$value}++
}
0

精彩评论

暂无评论...
验证码 换一张
取 消