Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

Here's the fastest and shortest way I could find to process an input file, and print the unique lines inside it:

perl -ne "$s{$_} ||= print" < in > out

Explanation: The ||= operator has a behaviour called "short-circuit". If the left-hand side of the operation evaluates to true, the operation will short-circuit and stop - essentially the right-hand side will be ignored and never evaluated. But if the left side is false, then whatever the right-hand side evaluates to will be assigned to the left.

In this case, we are processing each line from a file called "in". The first time we see $s{$_} it will evaluate to false, setting off the right hand side to be evaluted. This will print $_, return a 1, then set $s{$_} to 1.

The next time we see $s{$_} inside the loop, it is true, so the ||= never again runs the right-hand side operation. This results in the above code only printing a line the first time it's seen, and no more.


In reply to (dkubb) Re: (2) Printing unique lines in a file by dkubb
in thread == uniq by northface

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others sharing their wisdom with the Monastery: (5)
As of 2024-03-29 12:15 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found