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

Re: Simple Table structure to file

by ultibuzz (Monk)
on Jan 23, 2007 at 10:22 UTC ( #596061=note: print w/replies, xml ) Need Help??

in reply to Simple Table structure to file

after smathing and throwing some office stuff the blockade is gone and i managed to code somthing that is working but is far away from being nice code

#!"C:\perl\bin\perl.exe" use warnings; use strict; open(IN, '<', "traffic_compare.txt") or die("open failed: $!"); my @tmp; while (<IN>) { chomp; push @tmp,(split(';',$_))[0]; } close(IN); my @tmp_new= do { my %seen;grep !$seen{$_}++, @tmp }; my %table_hoa; foreach my $groups (@tmp_new) { open(IN, '<', "traffic_compare.txt") or die("open failed: $!"); while (<IN>) { (my $id, my $value) = split(';',$_); if ($id == $groups) { push @{ $table_hoa{$groups} }, $value; } } close(IN); }

thanks for the hints, and are there any idears how to amke this code a bit nicer ?
i don't like this @tmp pushing everything in there removing the duplicates

kd ultibuzz

Replies are listed 'Best First'.
Re^2: Simple Table structure to file
by davorg (Chancellor) on Jan 23, 2007 at 10:48 UTC

    Actually, now I think about it, as you're potentially dealing with duplicates (I assume that's why you're using a %seen hash) then a hash of hashes might be simpler.

    my %data; while (<IN>) { chomp; my @vals = split /;/; $data{$vals[0]}{$vals[1]}++; }

    You then have a hash where the keys are your first set of values (12, 01, etc) and each value in the hash is reference to another hash where the keys are the second (longer) values and the values are the number of times each of those values appears in the data (which, I think, can be ignored for your purposes).

    Then you can get the output you want like this:

    foreach my $key (keys %data) { print "$key;"; print join(';', keys %{$data{$key}}); print "\n"; }

    "The first rule of Perl club is you do not talk about Perl club."
    -- Chip Salzenberg

Re^2: Simple Table structure to file
by virtualsue (Vicar) on Jan 23, 2007 at 10:42 UTC
    It seems to me that you are not taking advantage of the way hashes operate in Perl, so your code is doing far more work than necessary. If you use the code template I gave you, and plug in the split and the push, you'll be home in time for dinner. Try it with some sample data from your file in the __DATA__ section, or bang in your own file open and change the filehandle.

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (8)
As of 2019-12-10 13:21 GMT
Find Nodes?
    Voting Booth?

    No recent polls found