in reply to Edit html files in directory

Update: The above solutions are probably better, but I'm leaving this in the hope it helps clarify things.

I think the problem that you were having was due to trying to open all the results from the directory list, including "." and ".."

The code below, should fix that and I've added a quick stab at the regex you're after.

#!/usr/bin/perl use strict; use warnings; opendir(DIR, "."); my @list = readdir(DIR); closedir(DIR); foreach my $file (@list){ #the line below makes sure you don't try to open . and .. if($file !~ /^\.+$/){ open(FILE,"$file"); my @lines = <FILE>; close FILE; # Open same file for writing, reusing STDOUT open (FILE, ">$file") or die "Can't open $file: $!\n"; # Walk through lines... foreach my $line ( @lines ) { #can just make the replacement on this line $line =~ s/(\w+_[_\w]+)\(\)/<A HREF="$1.html">$1\(\)<\/A>/; print FILE $line; } close FILE; } } closedir( DIR );

Replies are listed 'Best First'.
Re^2: Edit html files in directory
by hilitai (Monk) on Aug 22, 2007 at 14:15 UTC
    I think johnlawrence is correct here, the problem is that you are trying to open everything returned by readdir(), which will include the current and parent directories, not just the plain files.

    It would be clearer, though, if you gave us the complete output. Can you tell which die() statement it failed on? (This is a good reason for making the message text from die() action specific -- if it dies trying to open a file for reading, say so. die "Can't open $file for reading: $!" and die "Can't open $file for writing: $!" make it a lot easier to tell just where it died.)

Re^2: Edit html files in directory
by Anonymous Monk on Aug 22, 2007 at 14:32 UTC
    Hi, thanks for your reply, you've been a great help.

    Ive noticed that the regex youve had a go at doesnt replace all instances on a line, only the first one...

    e.g.
    x_x(), y_y_y(), z_z()

    becomes:
    <a href="x_x.html">x_x()</a>, y_y_y(), z_z()

    How might i change this, use a * to apply to all instances?..

    s/(\w+_[_\w]+)\(\)/<A HREF="$1.html">$1\(\)<\/A>/*;

    Thanks again

      \w includes an underscore, so your regex \w_[_\w]+ will match ___ which probably isn't what he wants.

      Clint

      Ah...use g for global after the last delimiter :)