in reply to parsing

#!/usr/bin/perl -w use strict; $|++; use Time::Local; my $online = [ map { timelocal( (split /[:\/\s]+/)[2,1,0,4,3,5] ) } <DA +TA> ]; my $total = 0; for ( local $_ = 0; $_ <= $#{$online}; $_ += 2 ) { $total += $online->[$_+1] - $online->[$_]; } print "$total seconds online\n" __DATA__ 10:09:55 05/28/00 Sunday 10:37:45 05/28/00 Sunday 09:27:02 05/29/00 Monday 09:34:05 05/29/00 Monday 20:48:00 05/29/00 Monday 20:57:19 05/29/00 Monday 21:38:32 05/29/00 Monday 21:40:14 05/29/00 Monday 09:32:50 05/30/00 Tuesday 09:37:29 05/30/00 Tuesday 13:03:23 05/30/00 Tuesday 13:09:45 05/30/00 Tuesday
Enjoy!
--
Casey

Replies are listed 'Best First'.
RE: Re: parsing
by toadi (Chaplain) on Jul 27, 2000 at 11:52 UTC
    I never used map before, I read the docs but don't really understand it. Can you make it a bit more clear what it just does?

    --
    My opinions may have changed,
    but not the fact that I am right

      The easiest way to think of map is to reduce it to something a bit more familiar.
      @result = map SOME_EXPRESSION, @input;
      can be replaced with:
      @TEMP = (); foreach $_ (@input) { push @TEMP, SOME_EXPRESSION; } @result = @TEMP;
      In other words, evaluate SOME_EXPRESSION for each @input item, and take the result(s) of that, concatenated together, to make an output. While the expression is being evaluated, $_ contains the "current item" from @input.

      -- Randal L. Schwartz, Perl hacker

      This should probably be a Q&A but, "I understand your pain" in regards to map. Up until _very_ recently I didn't really understand it either (probably still don't -not like the true monks) but here goes:

      Map executes a block of code for each element in a list and returns a list of the results. The magical variable $_ is set (actually localized so it isn't clobbered outside the block) to each element within the block. Map is _extremely_ powerful when in the hands of the likes of merlyn and friends. (i.e. Schwartzian Transform)
      A couple (simple) examples to illustrate:
      copy a list (i.e. do nothing same as @b = @a;)

      @b = map {$_} @a;

      Take a list of numbers (a vector) square them, add them together and take the square root (Euclidian N-dimensional distance):

       $dist = sqrt(eval join("+",map {$_**2} @a));

      Explanation of that last one: map squares each element in @a (say 1,2,3,4,5) and returns a new list (1,4,9,16,25) then join makes a scalar "1+4+9+16+25", the eval makes it 55 and finally sqrt returns 7.41619... which is assigned to $dist.

      For another example see A minor epiphany with grep and map as well as every piece of documentation on the topic you can get your hands on. I think what did it for me (finally) was Effective Perl Programming by Joseph N. Hall with Randal L. Schwartz. The section (Item 12) is only 4 pages long and also covers grep and foreach but, it was the lightswitch for me.
      -ase