How can I remove the title name of each unique number in Data::Dumper in perl?

83 Views Asked by At

I use Data::Dumper to catch uniqe number in each element.

#!perl

use warnings;
use strict;
use Data::Dumper;
$Data::Dumper::Sortkeys = 1;

my @names = qw(A A A A B B B C D);
my %counts;
$counts{$_}++ for @names;
print Dumper (\%counts);

exit;

This is output.

$VAR1 = {
          'A' => 4,
          'B' => 3,
          'C' => 1,
          'D' => 1
        };

How can I remove the title name of each unique number to get output like this format?

$VAR1 = { 4 ,3 ,1 ,1 }
2

There are 2 best solutions below

0
ikegami On BEST ANSWER

Presuming you want the counts in descending order, you could use the following:

printf "\$VAR1 = { %s};\n",
   join ',', 
      map "$_ ",
         sort { $b <=> $a }
            values(%counts);

If instead you want the counts sorted by key,

printf "\$VAR1 = { %s};\n",
   join ',', 
      map "$counts{$_} ",
         sort
            keys(%counts);

Either way, that's a really weird format. Square brackets would make more sense than curly ones.

2
Polar Bear On

One of many ways to get desired result

use strict;
use warnings;

use feature 'say';

my @names = qw( A A A A B B B C D );

my %counts;

$counts{$_}++ for @names;

my @values = map { $counts{$_} } sort keys %counts;

say join(',', @values);

output

4,3,1,1