http://qs321.pair.com?node_id=600208


in reply to Grepping arrays, any better way to do this?

bart,izut,akho thank you for your wonderful comments and code.
I'd like to know more on whats happening in izut's code, most specifically the map and unpack part.

Thank you once again
  • Comment on Re: Grepping arrays, any better way to do this?

Replies are listed 'Best First'.
Re^2: Grepping arrays, any better way to do this?
by 5mi11er (Deacon) on Feb 16, 2007 at 23:00 UTC
    # creates a hash with all dates seen on @fileslist my %seen_dates; @seen_dates{ map { ( unpack( "x6A*", $_ ) )[0] } @fileslist } = (); # increases the value of each seen @datelist element on %seen_dates. foreach (@datelist) { if ( exists $seen_dates{$_} ) { $seen_dates{$_}++; } }
    This code is commented already with what it is doing. The map/unpack stuff is "magically" iterating over the array @fileslist, and unpacking each entry therein. map is the iterator, it takes expressions or a block of code as the thing to do with each element in a given list. Unpack is ignoring 6 bytes of data, and then grabbing the rest as ascii text. Since unpack can return a list itself, the author was careful to specifically ask for exactly the first element of the one element list. (that's the ')[0]' part right after the unpack), then for each thing in this new list, create an empty hash entry.

    The upshot of all that is that it creates a hash entry for each 'date' portion of the files in fileslist. Then once the hashes are created, it goes through the date list, and for each date within this hash, if it is in the date list, the hash entry is incremented. (that's the foreach section of code).

    Actually that code is not written to work correctly, as the first part is creating empty lists/arrays of hashes not simple hashes anyway...

    It is likely that the seemingly tortuous example given was to

    • try to teach you something by getting you to figure this stuff out yourself, and
    • keep you from actually using that in a homework assignment
    You'll notice I've not given you simpler to understand code for this same reasons.

    -Scott