Abimael Martinez wrote:
Hi,

Hello,

I am having some problems making this little script work, it is supposed glob files from current dir, and add stuff at the top and bottom of such files. I am also unshure how the "autoflush" works.


use strict;
use IO::File;
use IO::Handle qw( );

my @web_docs = <*.html>;
my @excluded = qw/ sidebar.html /;      


foreach my $doc_name ( @web_docs ) {
# This joins all the filenames in a (filename1|filename2|...) form to # match with a regex
        my $re = join '|', map{quotemeta} sort 
{length($b)<=>length($a)}...@excluded;
        # This compiles the regex
        $re = qr/($re)/;

You never modify @excluded inside the loop so $re should be defined outside the loop instead. You are using this to match file names but it is not anchored so it may match more file names than you intended. You are using capturing parentheses in your regular expression but you do not use the results of that capture.

my $re = '\A(?:' . join( '|', map "\Q$_", sort { length $b <=> length $a } @excluded ) . ')\z';
$re = qr/$re/;

foreach my $doc_name ( @web_docs ) {


        # Next if $doc matches any of the docs I which to keep unmodified
        next if ($doc_name =~ $re);
        &add_div("content", $doc_name);
}

sub add_div {
# Get the stuff my $div_id = shift @_; my $file_name = shift @_;
        # Create file handle
        my $file = new IO::File;
# Open a temporary file handle
        my $tmp = new_tmpfile IO::File;
# Open the document $file->open ("+< $file_name"); print "Couldn't open $file_name" unless (defined $file);

If the file could not be opened you are going to print out a message and then continue on as if the file had been opened correctly? You should also include the $! variable in the error message so you know why the file could not be opened.


        #$file->autoflush(1);
        #$tmp->autoflush(1);
        #autoflush STDOUT 1;
my $div_start = "<div id=" . '"' . $div_id . '">' . "\n\n";

Or:

        my $div_start = qq[<div id="$div_id">\n\n];


        print {$tmp} "$div_start";

Why are you copying $div_start to a string when print() will already convert it to a string.


        print {$tmp} <$file>;
my $div_end = "\n\n</div>";
        
        print {$tmp} "$div_end";

        print {$file} <$tmp>;

        $file->close;
$tmp->close;
}


John
--
The programmer is fighting against the two most
destructive forces in the universe: entropy and
human stupidity.               -- Damian Conway

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to