Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re: goto HACK

by cavac (Parson)
on Sep 25, 2018 at 09:30 UTC ( [id://1222955]=note: print w/replies, xml ) Need Help??


in reply to goto HACK

If you only have timestamps, you can just count them:

#!/usr/bin/env perl use strict; use warnings; use Data::Dumper; my @times = qw(1000 1000 1000 1010 1010 1010); my %data; foreach my $key (@times) { $data{$key}++; } print Dumper(\%data);

Results:

$ perl timehash1.pl $VAR1 = { '1000' => 3, '1010' => 3 };

On the other hand, if you have data associated with the timestamps, you can just push that data into an array associated with that specific timestamp inside the hash. Sounds complicated, but it isn't:

#!/usr/bin/env perl use strict; use warnings; use Data::Dumper; my @times = (1000 => 'hello',, 1000 => 'world', 1000 => 'foo', 1010 => 'bar', 1010 => 'baz', 1010 => ['hello world', 'hallo welt'], ); my %data; while(@times) { my ($key, $val) = (shift @times, shift @times); push @{$data{$key}}, $val; } print Dumper(\%data);

And here is the result:

$ perl timehash2.pl $VAR1 = { '1010' => [ 'bar', 'baz', [ 'hello world', 'hallo welt' ] ], '1000' => [ 'hello', 'world', 'foo' ] };

Edit: If you want to avoid temporary variables, you can also make the main loop faster but harder to read:

while(@times) { push @{$data{shift @times}}, shift @times; }
"For me, programming in Perl is like my cooking. The result may not always taste nice, but it's quick, painless and it get's food on the table."

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others cooling their heels in the Monastery: (2)
As of 2024-04-26 03:35 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found