Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Re: Very basic question while reading a file line by line

by atcroft (Abbot)
on Dec 10, 2022 at 01:45 UTC ( [id://11148699]=note: print w/replies, xml ) Need Help??


in reply to Very basic question while reading a file line by line

Q: How would you do it manually?
A: You would recall which you have already seen, and only output if it were not in that list.

Q: How to do that in code?
A: One way would be to put the name into a hash, and only output if it were not present. In my example code below (which I used data from an array instead of a file, but the logic within the while loop is the same as if processing a file), I split the line into two (2) parts based on m/\s+/ (one or more whitespace characters, which could be spaces, tabs, etc). I then check if the name exists as a key in the hash (%seen); if not, I output the line. After the check, I increment the value of the hash element with the name as the key.

Output:

$ ./11148698-00.pl id name 123 john 11 peter 87 helen

Code:

#!/usr/bin/env perl use strict; use warnings; use utf8; my @data = ( q/id name/, q/123 john/, q/34 john/, q/567 john/, q/11 peter/, q/899 peter/, q/87 helen/, ); my %seen; while ( my $str = shift @data ) { chomp $str; my @part = split /\s+/, $str, 2; if ( not exists $seen{ $part[1] } ) { print $str, qq{\n}; } $seen{ $part[1] }++; } print qq{\n};

Hope that helps.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (2)
As of 2025-12-14 13:10 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    What's your view on AI coding assistants?





    Results (94 votes). Check out past polls.

    Notices?
    hippoepoptai's answer Re: how do I set a cookie and redirect was blessed by hippo!
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.