Process, String and Mathematical Functions

Perl provides a wide range of functions that manipulate both the program currently being executed and other programs (also called processes) running on your machine, they are divided into four groups

Starting a Process

Several built-in functions provide different ways of creating process

eval The eval function treats a character string as an executable Perl program. Eval function is best used for small programs for large programs it is better to use the system function
system When system is called it starts a process that runs the program passed to it and waits until the process terminates. This function is passed a list as follows; the first element of the list contains the name of a program to execute and the other elements are arguments to be passed to the program .
fork

The fork function creates two copies of your program, the parent process and the child process. Fork returnes zero to the child process and a non-zero value to the parent process, this non-zero value is the process ID of the child process.

Becareful when using fork

  • if both copies of the program execute calls to print or any other output-generating function, the output from one copy might be mixed with the output from the other copy.
  • if you use fork in a loop, the program might wind up generating many copies of itself.
  • your child process might wind up executing code that your parent process is supposed to execute, or vice versa.
pipe The pipe function is designed to be used in conjunction with the fork function. It provides a way for the child and parent process to communicate.
exec The exec function is simular to the system function, except that it terminates the current program befre starting a new one. This function is passed a list as follows; the first element of the list contains the name of a program to execute and the other elements are arguments to be passed to the program.
syscall The syscall calls a system function, This function is passed a list as follows; the first element of the list contains the name of a program to execute and the other elements are arguments to be passed to the program
Examples
eval

## Example one
$print = "print (\"hello world\\n\");";
eval ($print);

## Example two (this has a error)
$print = "print (\hello world\\n\");";     # I have removed a double quote
eval ($print);
print "Errors: " . $@                      # $@ will contains the error message

Note: the $@ system variable is used to indicate if the statement was executed properly, if no error $@ contains null, if any errors $@ will have the error message

system

@proglist = ("echo", "hello", "world");     # echo is the program, hello world are the arguments to echo
system(@proglist);

Note: sometimes it is use to use the below command to make sure that buffers are flushed immediately, as sometimes calling two systems duplicate outp[ut can be mixed

$| = 1;       # make sure output buffers are flushed immediately.

fork

print "Parent PID: " . $$ . "\n";

$retval = fork();

if ($retval == 0) {
   # this is the child process
   print $retval . "\n";
   print "Child PID: " . $$ . "\n";
   exit;
} else {
# this is the parent process
}

Note: to terminate a child process you use the exit function which is discussed lter

pipe # pipe (infile, outfile)
pipe (INPUT, OUTPUT);     # Data sent to OUTPUT can be read from INPUT

$retval = fork();

if ($retval != 0) {
   # this is the parent process
   close (INPUT);         # the parent process does not need INPUT
   print "Enter a line of input: ";
   $line = <STDIN>;
   print OUTPUT ($line);
} else {
   # this is the child process
   close (OUTPUT);        # the child process does not need OUPUT
   $line = <INPUT>;       # because data from OUTPUT is piped into INPUT, the program waits until the
                          # data is actually sent before continuing
   print ($line);
   exit(0)
}

exec

exec ("vi", "test.pl");

Note: exec has the same buffering problems as system

syscall

require ("syscall.ph");   # must have the syscall header

my $buf = "\0"x64;
my $path = "/etc/motd";

syscall(&SYS_statfs, $path, $buf) == 0 or die;

my ($bsize, $blocks, $bfree, $bavail, $files, $ffree, $namelen) = unpack "x4 L6 x8 L", $buf;

print <<EOT;
   Optimal transfer block size: $bsize
   Blocks in file system: $blocks
   Blocks free: $bfree (${\(int $bfree/$blocks*100)}%)
   User blocks available: $bavail (${\(int $bavail/$blocks*100)}%)
   Inodes: $files
   Free inodes: $ffree (${\(int $ffree/$files*100)}%)
   Maximum filename length: $namelen
EOT

Terminating a Program or Process

Several built-in functions provide different ways of terminating a program or process

die The die function terminates a program and prints an erropr message on the standard error file
warn The warn function like the die function prints a message on the standard error file but does not terminate the program
exit The exit function terminates a program and can optionally return a code value.
kill The kill function enables you to send a signal to a group of processes.
Examples
die die ("message");         # prints the message and program name and line number where the error occurred
die ("message\n");       # only prints the error message
warn warn ("message");        # prints the message and program name and line number where the error occurred
warn ("message\n");      # only prints the error message
exit exit();
exit(8);                 # exits and retruns the code 8
kill @proclist = qw(5555 5556 5557);

kill (9, @proclist);     # send a kill signal 9 to processes 5555 5556 5557

Execution Control

Several built-in functions provide different ways of to delay a program or process

sleep The sleep function suspends the program for a specified number of seconds
wait The wait function suspends execution and waits for a child process to terminate (such as a process created by fork)
waitpid The waitpid function waits for a particular child process.
Examples
sleep sleep (5);                # sleep for 5 seconds;
wait wait();                   # wait returns the process ID, -1 is returned if no child process exists
waitpid

# waitpid (<procid>,<waitflag>)

$procid = fork();                                    # obtain the child process ID

if ($procid == 0) {
   # this is the child process
   print ("CHILD: this line is printed first\n");
   exit(0);
} else {
   # this is the parent process
   waitpid ($procid, 0);                              # wait until child process finishes
   print ("PARENT: this line is printed first\n");
}

Note: the waitflags are
0  - normal wait
1  - process has been found and has terminated
-1 - child process does not exist

Miscellaneous Control Functions

Several built-in functions provide different ways of to perform various process and program-related actions

caller

The caller function returns the name and line number of the program that called the currently executing subroutine.

caller returns a three-element list subinfo consisting of the following

  • The name of the package from which the subroutine was called
  • The name of the file from which the subroutine was called
  • The line number of the subroutine call

The function is mainly used with the perl debugger.

chroot The chroot function duplicates the functionality of the chroot function call.
local The local function declares that copy of a named variable is to be defained for a subroutine
times

The times function returns the amount of job time consumed by this program and any child processes of this program

times returns timelist a list consisting of the following pointing float numbers

  • The user time consumed by this program
  • The system time consumed by this program
  • The user time consumed by child process
  • The system time consumed by child process
Examples
caller test();

sub test {
   ($package, $file, $line_num) = caller;

   print "Package: " . $package . "\n";
   print "File: " . $file . "\n";
   print "Line Number: " . $line_num . "\n";
}

chroot # chroot(dir)
chroot ("/export/home/pvalle");      # the specified directory becomes the root directory for the program
local

if ( $var == 44) {
   local ($localvar);                # this is a local variable and does not affect any other $localvar's
}

Note: becarefuil when using loops as you can create alot of local variables

times $procid = fork();

($user,$system,$cuser,$csystem) = times;   # The four element list is returned

if ($procid == 0) {
   # this is the child process
   print ("CHILD: this line is printed first\n");
   exit(0);
} else {
   # this is the parent process
   waitpid ($procid, 0); # wait until child process finishes
   print ("PARENT: this line is printed first\n");
}

print "User: " . $user . "\n";
print "System: " . $system . "\n";
print "Child User: " . $cuser . "\n";
print "Child System: " . $csystem . "\n";

Mathematical Functions

Perl provides lots of mathematical functions

sin pass in a scalar value and the sine value is returned
cos pass in a scalar value and the cosine value is returned
atan2 calculates and returns the arctangent of one value dividend by another in the range -∏ to ∏
sqrt returns the square root value of the value passed
exp returns the e ** value
log takes a value and returns the natural (base e) logarithm of the value
abs returns the absolute value of a number
rand passed a integer value and returns a random floating point number between zero and value passed
srand use the random number generator used by rand, this ensures that the random numbers are truely random
Examples
sin $retval = sin (<value>);
cos $retval = cos (<value>);
atan2 $retval = atan2 (<value1>, <value2>);
sqrt $retval = sqrt (<value>);
exp $retval = exp (<value>);
log $retval = log (<value>);
$retval = log (exp ($var));      # The log function undoes exp expression
abs $retval = abs (<value>);
rand $retval = rand(<num>);           # any random number between 0 and specified number
srand $retval = srand(<num>); 

String-Manipulation Functions

There are many functions that can manipulate strings

index provides a way of indicating the location of a substring in a string
rindex the same as index but starts at the right-hand side of the string
length returns the number of characters of a string
tr the translate functions translates character from one set into a diffferent set, you can also obtain the number of characters in a string
pos returns the location of the last pattern match in a string, you can use the global pattern match operator.
substr lets you assign a part of a character string to a scalar variable
study is a special function that tells the interpreter that the specified scalar variable is about to be searched many times.
lc and uc lc converts a string to lower case, uc converts a string to upper case
lcfirst and ucfirst lcfirst converts the first character of a string to lower case, ucfirst converts the first character of a string to upper case
quotemeta places a \ in front of any non-words
join takes a list and joins it into a single string
sprintf The sprintf function is the same as the printf function, except that the formated string is returned by the function instead of being written to a file
Examples
index

# position = index (string, substring)
# position = index (string, substring, skip characters)

$string = "elephant";
$position = index($string, "ant");

print "ant is located at position " . $position . " in elephant";

rindex

# position = rindex (string, substring)
# position = rindex (string, substring, skip characters)

$string = "elephant";
$position = rindex($string, "ant");

print "ant is located at position " . $position . " in elephant";

Note: the only different with index and rindex is thet rindex starts at the right hand side of the string

length $string = "elephant";

print "There are " . length($string) . " characters in elephant";
tr $string = "elephant";
$_ = $string;                    # tr uses the system variable $_;

$new_string = tr/a-z/A-Z/;       # new string goes in $_, number of characters change is returned

print "We have changed " . $string . " to " . $_ . "\n";
print $string . " has " . $new_string . " characters"

pos

$string = "Mississippi";

while ($string =~ /i/g) {
   $position = pos($string);
   print ("matched at position $position\n");
}

substr

# substr (expr, skipchars, length)

$string = "This is a simple character string";

$sub1 = substr($string, 10 , 6);       # skip 10 characters, get next 6 characters
$sub2 = substr($string, 17);           # skip 17 characters, get the rest of the string

print '$sub1 is ' . $sub1 . ' and $sub2 is ' . $sub2;

study study ($myvar);
lc and uc $lower = lc("Hello");                  # returns hello
$upper = uc("hello");                  # returns HELLO
lcfirst and ucfirst $lcfirst = lcfirst("Hello");           # returns hello
$ucfirst = ucfirst("hello");           # returnsd Hello
quotemeta $string = "Hello World";

$newstring = quotemeta($string);

print $string . "\n";
print $newstring;                      # prints 'Hello\ World'

join @list = qw ( hello what a wonderful day);

$string1 = join( "::", @list);
$string2 = join( " ", @list);

print $string1 . "\n";
print $string2;

sprintf

$num = 26;
$outstr = sprintf("%d = %x hexadecimal or %o octal\n", $num, $num, $num);

print $outstr;