6

Using Text::Ngram I have

my $c = ngram_counts($text, 3);
my %ct = %($c);

which doesn't work (Scalar found where operator expected). I think this is a combination of not knowing what I'm doing (still not very good with Perl) and being confused about what exactly I'm getting as output from Text::Ngram. Help? I just want to look at the generated n-grams:

my @keys = sort {$ct{$a} cmp $ct{$b} } keys %ct;
foreach my $k (@keys) {
    print "$k: $ct{$k}\n"
}

Edit: Stupid error on my part, thanks everyone.

Zaid
  • 36,680
  • 16
  • 86
  • 155
Charles
  • 11,269
  • 13
  • 67
  • 105

4 Answers4

16

Use curly braces to dereference the hash reference:

my %ct = %{ $ct };  # %$ct would also work

And you probably want to use <=> for numerical sorting instead of the ASCII-betical sorting cmp.

Zaid
  • 36,680
  • 16
  • 86
  • 155
7

Use curly braces:

my %ct = %{ $c };
gpojd
  • 22,558
  • 8
  • 42
  • 71
3

There's no need to make a copy into another hash, just use the reference.

my $c = ngram_counts($text, 3);

my @keys = sort {$c->{$a} <=> $c->{$b} } keys %$c;
foreach my $k (@keys) {
    print "$k: $c->{$k}\n"
}

See http://perlmonks.org/?node=References+quick+reference for some easy to remember rules for dealing with references.

ysth
  • 96,171
  • 6
  • 121
  • 214
0

Would you try this?

my $c = ngram_counts({}, $text, 3);
sergio
  • 68,819
  • 11
  • 102
  • 123