'How to group hash of numbers that are equals

I'm kinda new to programming and Perl... I would say I could do that in C like language, but I've got no idea how to do that in Perl.

To simplify things...

my $sql = [
    { ID => 1 },
    { ID => 2 },
    { ID => 2 },
    { ID => 2 },
    { ID => 3 }
];

my $number = 0;

foreach( @{ $sql } ) {

    my @array = (); 

    if ( $number != $_->{ ID } ) {

        push @array, $number;

        if( $number ) {
             push @array, '(' . $_->{ ID } . ')'; #how should I cycle that ?
        }
    }

    $number = $_->{ ID };

    print("@array");
}

I somehow need to get an output like this 1(2)(2)(2)3. I don't want to work with real code here, so I made a simple example how I use it now. I would be really grateful for help.

This code gives me 01 (2)2 (3) which is wrong. I've been thinking about it about for multiple hours so my results are getting worse and worse because I'm stuck and looping through the same mistakes.



Solution 1:[1]

Welcome to Perl and programming in general.

One straightforward way to do this is to count the number of times each value appears. If only once then print it without parentheses. If more than once then print it with parentheses and repeat according to the count for that value. I'm using the 'x' operator to repeat a string. '*' x 3 would give you '***' for example.

use strict;
use warnings;

my $sql = [
    { ID => 1 },
    { ID => 2 },
    { ID => 2 },
    { ID => 2 },
    { ID => 3 }
];

my $number = 0;

my %count_values;

foreach( @{ $sql } ) {
    # make the number the key, count how many times it appears.
    $count_values{$_->{ID}}++;
}

my $output_string = '';
foreach my $key_number ( sort {$a<=>$b} keys %count_values ){
    # if just one occurance then don't add parentheses.
    if ($count_values{$key_number} == 1){
        $output_string .= $key_number;
    } else {
        $output_string .= "($key_number)" x $count_values{$key_number};
    }
}

print $output_string;
    

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1