Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl - Hash of hash and columns :(

I've a set of strings with variable sizes, for example:

AAA23

AB1D1

A1BC

AAB212

My goal is have in alphabetical order and unique characters collected for COLUMNS, such as:

first column : AAAA

second column : AB1A

and so on...

For this moment I was able to extract the posts through a hash of hashes. But now, how can I sort data? Could I for each hash of hash make a new array?

Thank you very much for you help!

Al

My code:

#!/usr/bin/perl

use strict;
use warnings;

my @sessions = (
    "AAAA",
    "AAAC",
    "ABAB",
    "ABAD"
);

my $length_max = 0;
my $length_tmp = 0;

my %columns;

foreach my $string (@sessions){

    my $l = length($string);

    if ($l > $length_tmp){
            $length_max = $l;
    }
}

print "max legth : $length_max\n\n";

my $n = 1;

foreach my $string (@sessions){

    my @ch = split("",$string);

    for my $col (1..$length_max){
        $columns{$n}{$col} = $ch[$col-1];
    }

    $n++;
}

foreach my $col (keys %columns) {

    print "colonna : $col\n";

    my $deref = $columns{$col};

    foreach my $pos (keys %$deref){
            print " posizione : $pos --> $$deref{$pos}\n";
    }

    print "\n";
}

exit(0);
like image 864
alfonso Avatar asked Nov 05 '22 11:11

alfonso


1 Answers

What you're doing is rotating the array. It doesn't need a hash of hash or anything, just another array. Surprisingly, neither List::Util nor List::MoreUtils supplies one. Here's a straightforward implementation with a test. I presumed you want short entries filled in with spaces so the columns come out correct.

#!/usr/bin/perl

use strict;
use warnings;

use Test::More;
use List::Util qw(max);

my @Things = qw(
    AAA23
    AB1D1
    A1BC
    AAB212
);


sub rotate {
    my @rows = @_;

    my $maxlength = max map { length $_ } @rows;

    my @columns;
    for my $row (@rows) {
        my @chars = split //, $row;
        for my $colnum (1..$maxlength) {
            my $idx = $colnum - 1;
            $columns[$idx] .= $chars[$idx] || ' ';
        }
    }

    return @columns;
}


sub print_columns {
    my @columns = @_;

    for my $idx (0..$#columns) {
        printf "Column %d: %s\n", $idx + 1, $columns[$idx];
    }
}


sub test_rotate {
    is_deeply [rotate @_], [
        "AAAA",
        "AB1A",
        "A1BB",
        "2DC2",
        "31 1",
        "   2",
    ];
}


test_rotate(@Things);
print_columns(@Things);
done_testing;
like image 68
Schwern Avatar answered Nov 15 '22 05:11

Schwern