Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re: Frequency occurence of same words in a file -- oneliner

by Discipulus (Canon)
on Mar 25, 2022 at 08:28 UTC ( [id://11142407]=note: print w/replies, xml ) Need Help??


in reply to Frequency occurence of same words in a file

Hello geek12 and welcome to the monstery and to the wonderful world of perl!

as you already get sane and wise answers, I propose you a oneliner solution (change " to ' around the code to run it on Linux):

perl -lane "push @{$H{$F[0]}},$F[1]}{print map{$_,qq( ---> ),scalar @{ +$H{$_}},$/,(join $/,@{$H{$_}}),$/,$/}keys %H" data1.txt 0011 ---> 2 Sally Roy 1122 ---> 2 Brandon Simson 2233 ---> 1 George

You can use -MO=Deparse to have some clue on how to read it:

perl -MO=Deparse -lane "push @{$H{$F[0]}},$F[1]}{print map{ $_,qq( --- +> ),scalar @{$H{$_}},$/,(join $/,@{$H{$_}}),$/,$/ }keys %H" BEGIN { $/ = "\n"; $\ = "\n"; } LINE: while (defined($_ = readline ARGV)) { chomp $_; our @F = split(' ', $_, 0); push @{$H{$F[0]};}, $F[1]; } { print map({$_, ' ---> ', scalar @{$H{$_};}, $/, join($/, @{$H{$_}; +}), $/, $/;} keys %H); } -e syntax OK

See perlrun for perl command line switches, but basically -l takes care of line ending (you are not chomp -ing lines!), -a does autosplit populating the @F array and -n wraps the code in a while loop without printing ( and -p does the same but printing). Braces in the part ..$F[1]}{print.. are a trick named Eskimo Greeting.

See perlvar for $/ and @F

You can explore these switches deparsing them one at time like in ( -e is for execute perl code, and -e 1 is just a null program):

perl -MO=Deparse -l -e 1 BEGIN { $/ = "\n"; $\ = "\n"; } '???'; -e syntax OK perl -MO=Deparse -a -e 1 LINE: while (defined($_ = readline ARGV)) { our @F = split(' ', $_, 0); '???'; } -e syntax OK perl -MO=Deparse -n -e 1 LINE: while (defined($_ = readline ARGV)) { '???'; } -e syntax OK perl -MO=Deparse -p -e 1 LINE: while (defined($_ = readline ARGV)) { '???'; } continue { die "-p destination: $!\n" unless print $_; } -e syntax OK
L*

There are no rules, there are no thumbs..
Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.

Replies are listed 'Best First'.
Re^2: Frequency occurence of same words in a file -- oneliner
by geek12 (Novice) on Mar 25, 2022 at 17:15 UTC
    Hi, Will try this out. The first solution worked for me. I will go through the code you suggested as well and try it out and understand. thank you for the help.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11142407]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others perusing the Monastery: (7)
As of 2024-03-28 21:57 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found