Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Sorting files in perl ???

Status
Not open for further replies.

nattugan

Programmer
Aug 9, 2001
5
GB
I am new to perl and i am encountering few problems in the search that i am doing for a site that contains hundreds of html files. The following code that i have written actually finds out where the search string appears in all files. This also gives me a count of those files and filenames.

1. I want to sort file by their last modified time. Is using stat(<filename>) the only option. If so how do i sort. If i have to use 2-d arrays how would i do that.

2. I want the result to be displayed on a htm file. How should i go abt it.

Code:-
#!/usr/bin/perl
opendir(DIR,'.');
@files=sort(grep(/htm$/,readdir(DIR)));
closedir(DIR);
$tofind=&quot;<*>&quot;;
# string to search for
$expr=&quot;xyz&quot;;


$filecontent=&quot;&quot;;
$count=0;
$found=0;
$var=&quot; &quot;;
foreach(@files)
{
$icount=0;
@array=&quot;&quot;;
$filename=$_;
$filecontent=&quot;&quot;;
open(filename);
@array=<filename>;
close(filename);
foreach(@array)
{
if(m/$tofind/)
{
$_=&quot;&quot;;
}
s/$var//g;
# print $_;
$filecontent=$filecontent.$_;
$icount=$icount+1;
}
$_=$filecontent;
chomp();
print $_;
if(m/$expr/)
{
print($filename.&quot;\n&quot;);
$found=$found+1;
}
$count=$count+1;
print (&quot;Internal count for &quot;. $filename.&quot; is &quot;.$icount);
}
print &quot;The count is : &quot;.$count.&quot;\n&quot;;
print &quot;The pattern matched in &quot;. $found.&quot; files.\n&quot;;
print &quot;The internal count is :&quot;.$icount.&quot;\n&quot;;

Regards
Ganesh

 
To sort by last modified time, you'll need to use &quot;stat&quot; on each file to get the last modified time - create a hash key consisting of

1. the last modified time
2. the filename

when you're done loading the hash, you can sort it by the keys which will give the files listed in Last Modified Time order.

To display the results in an html file, just surround each line with proper html tags - but you also need proper html for the page your about to display - you're probably not ready for this yet. Do some reading on Perl CGI - the Learning Perl book for Schwartz & Christiansen has a whole chapter on CGI Programming, and that's a good place to start.

HTH.
Hardy Merrill
Mission Critical Linux, Inc.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top