get the current working directory
( categories: system )To get the pathname of the current working directory (like 'pwd' in a unix shell), use the 'cwd()' function from the module 'Cwd'.
Example:
#!/usr/bin/perl
#
#-- get current directory
my $pwd = cwd();
#-- change dir to /tmp
chdir("/tmp");
#-- do something there
do_something();
#-- go back to original directory
chdir($pwd);
In Windows systems, you have a current working directory for every drive available; Cwd provides on Windows systems the function 'getdcwd()' to obtain the current working directory of any drive.
execute commands on remote machines using ssh
( categories: system | perl modules )You can execute commands on remote machines from a Perl script using the Net::SSH::Perl module.
This module allows you to execute a command remotely and receive the STDOUT, STDERR, and exit status of that remote command.
One big advantage of Net::SSH::Perl over other methods is that you can automate the login process, that way you can write fully automated perl scripts, no console interaction is required in order to authenticate in the remote machine.
Example:
executing external commands
( categories: system )There are many ways to execute external commands from Perl. The most commons are:
- system function
- exec function
- backticks (``) operator
- open function
All of these methods have different behaviour, so you should choose which one to use depending of your particular need. In brief, these are the recommendations:
| method | use if ... |
| system() | you want to execute a command and don't want to capture its output |
| exec | you don't want to return to the calling perl script |
| backticks | you want to capture the output of the command |
| open | you want to pipe the command (as input or output) to your script |
check if a process is running
( categories: system )Send a 0 (zero) signal to the process ID you want to check using the kill function. If the process exists, the function returns true, otherwise it returns false.
Example:
#-- check if process 1525 is running
$exists = kill 0, 1525;
print "Process is running\n" if ( $exists );
determine the user and/or group running a script
( categories: system | special variables )Use the following predefined variables to get the user and group information belonging to the current process:
- $< - real user id (uid); unique value
- $> - effective user id (euid); unique value
- $( - real group id (gid); list (separated by spaces) of groups
- $) - effective group id (egid); list (separated by spaces) of groups
NOTES:
- This information applies only to Unix systems
- The values that theses variables hold are integers.
To get the user and group names, use '(getpwuid($<))[0]' (for user information) and 'getgrgid($()' (for groups).
