-4

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 }
Chen Leo
  • 17
  • 4

2 Answers2

2

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.

ikegami
  • 367,544
  • 15
  • 269
  • 518
1

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
Polar Bear
  • 6,762
  • 1
  • 5
  • 12