Search code examples
perldata-dumper

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


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 }

Solution

  • 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.