CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Intermediate:
Using pattern matching to change a file extension?

 



Nicko
Deleted

Sep 21, 2000, 9:16 AM

Post #1 of 4 (445 views)
Using pattern matching to change a file extension? Can't Post

Hello, first let me say that I hope that I am posting my question in the correct forum. My question is, I am trying to change a file extension using PERL's pattern matching capablities, but hit a slite snag. I have a small routine which reads in a directory, and it looks for all files with the extension .txt and converts them to .pr
The problem I am having is that if the file name contains txt in it such as 1txt.txt then my routine converts it to 1pr.pr.
This is the code I am using:

opendir(EXMP, "$BASEDIR/lists");

while ($files = readdir(EXMP))
{
if ($files =~ /.txt/)
{
$files =~ s/.txt/.pr/;
push (@lists, $files);
}
}
closedir(EXMP);


How can I get is so that it only changes the extension .txt to .pr?

Any help is greatly appreciated, and I thank you in advance.

Best regards,

Nicko
nicko@cheftalk.com


Kanji
User

Sep 20, 2000, 10:45 PM

Post #2 of 4 (445 views)
Re: Using pattern matching to change a file extension? [In reply to] Can't Post

You should anchor your expression to the end of the string since that's all you need ...

<BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR>

/\.txt$/</pre><HR></BLOCKQUOTE>

I add the \ before the . as . by itself will (usually) match any character, so \. will make sure you're only matching .txt and not atxt, xtxt, etc.

Also, you can save yourself some effor and combine the s/// and if ...

<BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR>

if ( $files =~ s/\.txt$/.pr/ ) {
push @lists, $files;
}</pre><HR></BLOCKQUOTE>

... because s/// will return true if it was successful, and false otherwise.


Nicko
Deleted

Sep 21, 2000, 1:12 PM

Post #3 of 4 (445 views)
Re: Using pattern matching to change a file extension? [In reply to] Can't Post

Kanji,

Thanks for the tip that really helps. One thing though, why do you put the $ after the .txt in:

$files =~ s/\.txt$/.pr/

Thanks,

Nicko


Kanji
User

Sep 21, 2000, 3:46 PM

Post #4 of 4 (445 views)
Re: Using pattern matching to change a file extension? [In reply to] Can't Post

As I said, you need to anchor your query to the end of the string which is done in perl regexp by the special meta-character $.

See perlre for more.

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives