0

I want to generate an output file that shows the frequency of each word inside an input file. After some search, I found that Perl is the ideal language for this problem, but I don't know this language.

After some more search, I found the following code here at stackoverflow, supposedly it provides the solution I want at great efficiency:

perl -lane '$h{$_}++ for @F; END{for $w (sort {$h{$b}<=>$h{$a} || $a cmp $b} keys %h) {print "$h{$w}\t$w"}}' file > freq

I tried running this command line using the form below:

perl -lane 'code' input.txt > output.txt

The execution halts due to an unexpected '>' (the one at '<=>'). I did some research but can't understand what is wrong.Could some one enlight me? Thanks!

Here is the topic from where I got the code:Elegant ways to count the frequency of words in a file

If it's relevant, my words use letters and numbers and are separated by a single white space.

Dada's user avatar
Dada
6,7657 gold badges28 silver badges48 bronze badges
askedMay 20, 2019 at 19:49
pedmacedo's user avatar
3

1 Answer1

5

You are probably using Windows. You therefore need to use doubles quotes" instead of singles quotes' around your code:

perl -lane "$h{$_}++ for @F; END{for $w (sort {$h{$b}<=>$h{$a} || $a cmp $b} keys %h) {print qq($h{$w}\t$w)}}" file > freq

Also, note how I usedqq() instead of"..." within the code, as suggested by @mob. Another option is to escape the quotes with\".

answeredMay 20, 2019 at 20:16
Dada's user avatar
Sign up to request clarification or add additional context in comments.

2 Comments

Will escaping the quotes work? If not, theqq{} syntax offers a workaround (print qq[$h{$w}\t$w]) .
@mob, I tried it on a Windows and it worked, but I'm not sure it works in every situation though. Gonna edit yourqq{} suggestion in ;)

Your Answer

Sign up orlog in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

By clicking “Post Your Answer”, you agree to ourterms of service and acknowledge you have read ourprivacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.