Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

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."

In reply to Re: goto HACK by cavac
in thread goto HACK by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chanting in the Monastery: (7)
As of 2024-04-16 11:31 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found