Although some appear to not understand the phrase "in Perl" in a node title, this type of loop is rather easy to do in Perl:

listTemplates | perl -ne 'chomp; unlink($_) or warn "Could not delete +$_: $!\n"'
(where "listTemplates" would be whatever existing commands you use to list the template file names).

perldoc perlrun has information on the -n and -e command-line options for perl. perl -ne '...' causes the '...' code to be run for each line read from STDIN (or from the listed files if I'd listed any files), with $_ set to be that line.

My solution assumes that the file names are listed one per line with no extra characters so chomp removes the newline from $_ so that it contains just a file name. If the file names are listed in some other way, then you'll need to do a little more work to extract the file names.

unlink deletes files. or checks whether unlink was successful and, if not, runs the following code which tells you *why* unlink failed (because I included $! in the message) and on which file.

You could also do something similar using the 'xargs' command, but it would probably be slower and harder to get it to handle extra text in the output (if there is any).

So I think you were wise to seek a Perl solution for this problem. Next time, mention "Perl" in the text of the node, not just the title, as some of us are a bit inobservant and/or cranky, unfortunately.

Update: Originally had "Can't" in my error message which interferes with the 'quoting' I used. I could have replaced it with "Can\'t", but chose to avoid contractions instead.

                - tye

In reply to Re: How to do loop in Perl (-ne) by tye
in thread How to do loop in Perl by hyliau

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.