You first read the whole XML file, then extract the 'name' attribute of the 'md' elements and then process them. This is perfectly valid, but given that you are interested only in a small part of the information, it is probably simpler to read the md elements and process the information (i. e. create the directories) as you go. XML::Twig is perfect for this kind of task:

#!/usr/bin/perl -w use strict; use XML::Twig; my $callout_loc = "."; my $file = "./mdlist.xml"; #create the parser (twig) #and tell it what sub to call if it finds an 'md' element my $twig = new XML::Twig (twig_handlers => {md => \&process_md}); #parse the file #process_md will be called every time an 'md' element is found $twig->parsefile ($file); #that's it exit 0; sub process_md { my ($t, $md) = @_; #get the name attribute my $name = $md->att ('name'); #create the dir unless it already exists my $dirname = "$callout_loc/$name"; unless (-d $dirname) { print "Creating $dirname...\n"; mkdir $dirname or die "Could not create dir $dirname: $!\n"; } else { print "$dirname already exists!\n"; } }
Much shorter, isn't it? And btw, I tested it, it works. HTH,

pike


In reply to Re: Read XML, Create Dir if not exist by pike
in thread Read XML, Create Dir if not exist by AcidHawk

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



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.