Perl - hash of hash and columns :(

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

AAA23

AB1D1

A1BC

Aab212

My goal is the alphabetical order and unique characters compiled for COLUMNS, for example:

first column: AAAA

second column: AB1A

etc.

At this point, I was able to extract the messages through a hash of hashes. But now, how can I sort the data? Can I create a new array for each hash hash?

Thank you so much for your help!

Al

My code is:

#!/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);
+5
source share
2 answers

, , - . - , . , List:: Util, List:: MoreUtils . . , , , .

#!/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;
+2

%columns

foreach my $i (sort { $a <=> $b } keys %columns) {
  print join(" " => sort values %{ $columns{$i} }), "\n";
}

A A A A 
A A A C 
A A B B 
A A B D

- , , . ,

sub columns {
  my @strings = @_;
  my @columns;

  while (@strings) {
    push @columns => [ sort map s/^(.)//s ? $1 : (), @strings ];
    @strings = grep length, @strings;
  }

  @columns;
}

,

A A A A
1 A A B
1 A B B
2 2 C D
1 1 3
2

, . Perl, , !

sub unique_sorted_columns {
  map { my %unique;
        ++$unique{$_} for @$_;
        [ sort keys %unique ];
      }
      columns @_;
}

, columns :

sub columns {
  my @strings = @_;
  my @columns;

  while (@strings) {
    my %unique;
    map { ++$unique{$1} if s/^(.)//s } @strings;
    push @columns => [ sort keys %unique ];
    @strings = grep length, @strings;
  }

  @columns;
}

:

A
1 A B
1 A B
2 C D
1 3
2
0

All Articles