Gossamer Forum
Home : General : Perl Programming :

a job for an associative array?

Quote Reply
a job for an associative array?
I am having problems with logistics. Here's what I want to do: a script gets a list of all (html) filenames in a directory tree, opens each file and gets the html title. It then prints out all titles, linked to the corresponding filenames.

Now, I have managed the first step and have all filenames in @files. For the next step, I did:
foreach $file (@files) {
open (FILE, "<$file") || die("Can't open $file.");
chomp(@file = <FILE>);
close (FILE);
$filedata = join("", @file);
if ($filedata =~ /(<title>)(.*?)(<\/title>)/) {
$title = $2;
push (@titles, $title);
}

At this point I got stuck. I have all filenames in @files, and all titles in @titles, but how do I display each title together with the corresponding filename?


kellner
Quote Reply
Re: a job for an associative array? In reply to
Hmmm....

Code:
my $dir = "/path";
my (@files, @links);
opendir(DIR, $dir) || die "Couldn't open $dir : $!";
@files = grep { /\.html$/i } readdir(DIR);
closedir(DIR);
Code:
foreach (@files) {
open(FILE, "<$dir/$_") || die "Couldn't open $dir/$_ : $!";
while (<FILE>) {
if (/(<title>)(.+)(<\/title>)/gi) {
push @links, "<a href=\"$dir/$_\">$2</a>";
} else {
push @links, "No title";
}
}
close(FILE);
}
No guarantees.

Installations:http://www.wiredon.net/gt/

Quote Reply
Re: a job for an associative array? In reply to
Thanks a lot. I picked up the code for the links - works wonderfully!
The rest is a bit more complicated, as the script is not just going through one directory, but through all its subdirectories and sub-sub-directories as well, and then first copies all files into a different directory.
Coincidentally: While I managed to get all subdirectories with File::Find and do the copying through File::Copy, would you know of any way to force perl to create directories if they don't exist?
Example:
directory /main/dir
directory /otherdir
All files and directories from /main are to be copied to /otherdir. Can perl be made to create /dir in /otherdir if it doesn't exist? And can this be coded in a somewhat simple fashion for all subdirs and possibly all subdirs of subdirs etc.?

kellner