http://qs1969.pair.com?node_id=233409


in reply to Read XML, Create Dir if not exist

Because Perl's motto is There's More Than One Way To Do It (TMTOWTDI), you'll probably find quite often that There's A Better Way To Do It Than You Could Think Of At The Time. But I think it's a good sign that you're willing to ask and to learn, and the code above looks like a good start.

One key change I'd suggest is to set your subs up so that they accept parameters and return values rather than relying on global variables directly. This is good habit to develop for a lot of reasons, and it will definitely pay off as you start to develop produce larger programs. For instance, you might rewrite Get_MDs like this:

sub Get_MDs { my ($mds) = @_; my @results; foreach $key (keys (%{$mds->{md}})) { push(@results, $mds->{md}->{$key}->{'name'} . $key); } return @results; }
Then you'd invoke the revised sub with a call like this:
my @mds = Get_MDs($mdlist);
This tends to make your code much more reusable, because you can store input and output in arbitrary variables.

It would also be a good idea to pass a directory name to checkdir explicitly, rather than relying on it to use the current value of $_.

Second, you're using map in a way that's considered less than ideal. map's purpose is to perform a function on each element of a list and construct a list from the results. So a typical use of map might look something like this: my @squares = map {$_**2} @numbers; In your code above, you're simply throwing away the results; a better alternative would be to replace map with a for construct:

checkdir($_) foreach (@mds)

Finally, I'd be inclined to replace your print "error"; exit code blocks with a single die "error" statement. die will direct output to STDERR rather than STDOUT and will terminate the program with a non-zero exit code, both of which can be useful if you want to execute the program from within another script (Perl or shell or otherwise).

Since die is a single command, it also lends itself to the following idiom:

die "problem: $@" if $@;
which is arguably more readable than the four lines it takes to do essentially the same thing following your eval, for example.

        $perlmonks{seattlejohn} = 'John Clyman';