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

Hi Monks, I'm creating a file that has two fields - a relay number and its state (e.g., relay1 reset/relay4 on/ relay10 initiate/relay1 set. Instead of a sequential file containing this data I'd like the relay with its accompanying states on one line: relay1 reset set...etc. What's the best way to do this - thanks!

Replies are listed 'Best First'.
Re: a use for hashes?
by ikegami (Patriarch) on Feb 01, 2010 at 18:36 UTC
    my %relays; while (<>) { my ($id, $state) = split ' '; push @{ $relays{$id} }, $state; } for my $id (keys(%relays)) { print("$id @{ $relays{$id} }\n"); }
      Thanks - that worked great! ..but it got me thinking. How could I do the same thing only instead of processing your code on a finished file if I could do the same thing as the file is being built? In other words, when code hits a relay that has already appeared with a state, the newly read state would be "pushed" along side of the previous one.
        Just replace the line that writes to the file with push @{ $relays{$id} }, $state;
Re: a use for hashes?
by Anonymous Monk on Feb 02, 2010 at 01:39 UTC
    my %states; # fill %states with data my $serialized = join('/', map {"$_ $states{$_}"} keys %states); print {$filehandle} $serialized;
Re: a use for hashes?
by Anonymous Monk on Feb 01, 2010 at 18:19 UTC
    What is the difference?
      currently (as the file appears) relay1 reset relay5 initiate relay3 set relay8 reset relay1 off relay5 running desired relay1 reset off relay5 initiate running hope this helps..