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 Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Code improvement 1

Status
Not open for further replies.

travs69

MIS
Joined
Dec 21, 2006
Messages
1,431
Location
US
I have 2 paths and only one will ever exist. I want to end up with a variable with the path that exists in it. I can do this with if/elsif's but I figure there's a better way :) I do not want to use any non default modules. I will be using the latest ActiveState build.

For Example:
Code:
$path1 = "/path/to/file1";
$path2 = "/path/to/file2";

if (-e $path1) { $fpath = $path1; }
elsif (-e $path2) { $fpath = $path2; }
else { die "Freakin out cause neither exist\n"; }

 
You maybe don't need to check if both files exists is the only real gain I see possible in our code. If one does not exist can you safely assume the other one does? The bigger concern is if you are using "strict"?

- Kevin, perl coder unexceptional!
 
I figured you would have a tricky reg exp or something... :)

If one exists I can assume that the other does not. I have some code that edits the hosts file. On some machines it's winnt is the base dir and on others its windows.

Travis
 
You would not use a regexp to see if a file exists. If you can assume one will always exist you could use the ternary opeator:

Code:
my $path1 = "/path/to/file1";
my $path2 = "/path/to/file2";
my $fpath = (-e $path1) ? $path1 : $path2;

fewer lines and maybe a little bit faster since it only checks for the existance of one of the files. File test operations are a relatively slow process so the fewer you do the faster your code should run. But the difference between doing one or two file tests can't be much.






- Kevin, perl coder unexceptional!
 
Don't mess about checking for files. On Windows the environment variable %SYSTEMROOT% is always set to the correct value. So $ENV{SYSTEMROOT} will always poin to the right directory.

Steve

[small]"Every program can be reduced by one instruction, and every program has at least one bug. Therefore, any program can be reduced to one instruction which doesn't work." (Object::PerlDesignPatterns)[/small]
 
Yeah... I thought about that to :) Just after I posted here
 
but are you looking for files or directories?

- Kevin, perl coder unexceptional!
 
The hosts file location will always be the same.. the only thing that change is the base dir. The SYSTEMROOT variable clarifies that. So there is no reason to check both places.. I just tack the path onto system root and check that.

$fpath = $ENV{SYSTEMROOT} . "/system32/drivers/etc/hosts";

or something close :)
 
ahh, I see now. [idea]

- Kevin, perl coder unexceptional!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top