Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Array unification problem has me in circles

by tsk1979 (Scribe)
on Nov 07, 2007 at 08:27 UTC ( [id://649430]=perlquestion: print w/replies, xml ) Need Help??

tsk1979 has asked for the wisdom of the Perl Monks concerning the following question:

Hi have data present in 3 arrays key1, key2 and data The number of elements in the three arrays is same. I have to write all the elements in a file as
$key1[0] $key2[0] $data[0] $key1[1] $key2[1] $data[1] . . . .
Pretty simple, eh? But there is a problem. If while parsing, a $data has appeared before, that should not be in the file. So lets say $data[45] has come before, in that case
$key1[45] $key2[45] $data[45]
Should not be dumped in the file. So I am uniquifying an array(which is pretty simple in itself), and controlling the printing of 2 other arrays using this. Any tips welcome!

Replies are listed 'Best First'.
Re: Array unification problem has me in circles
by graff (Chancellor) on Nov 07, 2007 at 09:02 UTC
    my %seen; for (0..$#data) { next if ( $seen{$data[$_]}++ ); print join "\n", $key1[$_], $key2[$_], $data[$_], ""; }
Re: Array unification problem has me in circles
by moritz (Cardinal) on Nov 07, 2007 at 09:03 UTC
    You can store strings in a hash as the hash keys, and while writing to your file you can always consult the hash to check if that key has already been printed.
Re: Array unification problem has me in circles
by tuxz0r (Pilgrim) on Nov 07, 2007 at 17:58 UTC
    I'm not sure how you are looping through those arrays, but an easy way to make @data contain only unique items might go like so:
    my %tmp = map { $_ => 1} @data; my @uniq_data = sort keys %tmp;
    Then, just use that to loop through the other structures, outputing defined keys only once.

    ---
    echo S 1 [ Y V U | perl -ane 'print reverse map { $_ = chr(ord($_)-1) } @F;'
    Warning: Any code posted by tuxz0r is untested, unless otherwise stated, and is used at your own risk.

      Or, written more cleanly:
      use List::MoreUtils qw( uniq ); my @uniq_data = uniq @data;

      My criteria for good software:
      1. Does it work?
      2. Can someone else come in, make a change, and be reasonably certain no bugs were introduced?

      Could avoid setting the 1s since values are absolutely being ignored, but it's a two step process ...

      my %tmp; @tmp{ @data } = ();

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (4)
As of 2024-04-19 17:47 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found