in reply to "du" to hash

I really really dislike the eval there. How about this instead?
use strict; use Data::Dumper; my %blocks; for (`du`) { (my $blocks, my $rest) = split; my @dirs = split /\//, $rest; my $where = \%blocks; while (@dirs) { $where = ($where->{shift @dirs} ||= {}); } $where->{""} = $blocks; } print Dumper(\%blocks);
The hash element with an empty string (an illegal directory name, important here) is the sum total of everything below it.

-- Randal L. Schwartz, Perl hacker

Replies are listed 'Best First'.
RE: RE: "du" to hash
by splinky (Hermit) on Jul 05, 2000 at 00:36 UTC
    First off, love the for loop. I didn't think of that. Out of curiosity, why do you dislike the eval? Just because evals are generally evil?

    *Woof*

      Two reasons to dislike the eval come to mind immediately:
      1. You are firing up the compiler over and over again to parse Perl code, when in fact the only part that is changing is the indicies and the depth of those. That means you're using a very general pile of code to handle a well-known predictable subset, and you'll burn far too much CPU to do that in the long run.
      2. More specifically here, you aren't escaping things like ` and { in the directory names, so you'll get invalid compilations from time to time, which you aren't checking for. These could also be potential security holes, since I merely have to create a directory with a name like `my-proggy` and you'll now be executing it! Shame.
      I consider any use of runtime eval to be a red flag during a code review session. There really has to be no other way to do something, and let me tell you, there's almost always more than one better way to do it.

      -- Randal L. Schwartz, Perl hacker