![]() |
Testing Filenames in Perl
When your script writes to a new file, you probably want it to create a new and unique name for the new file, one that doesn't conflict with any existing files, which would be overwritten. One way to create a new file name that's unique is to incorporate the process id and the time into the name. Perl's special variable, $$ returns the current pid and $^T returns the timestamp (in seconds since 1970). So you could use something like $filename = "$$" . "$^T" . ".html"; This alone will not guarantee uniqueness since there are only a finite number of process ids, which are recycled, and your script could have been accessed twice within the same second.
This also results in ugly filenames, something like "213031168857899.html". If you have prettier names that you insist on, you can test for the existence of a file with the proposed new name, using Perl's -e operator. -e $file_name is true if a file already exists with that name. In the example below, the variable $text holds some key text taken from the contents of the file that we want to use in the name. We're also assuming that the script is writing a web page, so we add ".html" as the extension. Code: Perl
|
Re: Testing Filenames in Perl
Many times not logic names are necessary, MD5 can be used in here.
I'm using something like: Code:
use strict;The $counter forces different text every time. |
Re: Testing Filenames in Perl
That's a really cool idea too, but most of the times we need the files to be named according to some logic!
|
Re: Testing Filenames in Perl
Logic parts can be added to the name ;)
But the important part is the cycle to find a acceptable name. Probably (I don't work with the web) many web servers are using a process for multiple requests, so the PID will be the same for this requests. Adding a counter can help. |
Re: Testing Filenames in Perl
Yes, quite right, web servers like Apache use threads to serve multiple requests. You code is perfect except for hashing.
I think, timestamp,PID and counter are enough to make the filename unique! |
Re: Testing Filenames in Perl
We can make a sub-routine out of this logic, like this,
Code: Perl
|
Re: Testing Filenames in Perl
Even better lets do $counter a global variable.
Quote:
|
Re: Testing Filenames in Perl
sory for the code
Code:
{ |
| All times are GMT +5.5. The time now is 00:06. |