2008年6月25日 星期三

Get host name in perl script.

Situation:

Want to get the host name which the perl script running on.

====

Solution:

The macro `hostname` helps us to get host name.
Note that `hostname` is not 'hostname'. You need to use `, the key which also send ~ on keyboard.

i.e.

$host_name = `hostname`;

Get the script location, full name rather than working directory.

Situation:

Want to get the location of the script rather than the working directory.
For example, there is a perl script "C:\ooxx\xxoo\aabb.pl". You want to get the directory "C:\ooxx\xxoo".

====
Solution:

For code,

use Cwd;

$workingDir = getcwd;

If you at "C:" and give the command "C:\ooxx\xxoo\aabb.pl", then the current working directory would be "C:".

To get "C:\ooxxx\xxoo", the location of the script, just use

$theSciptFullName = $0;

at the start of the code. When the script just start, the $0 stores the script's full path, that is "C:\ooxx\xxoo\aabb.pl". You can derive the location of the script from the script's full name.