system "whoami";The function system runs the whoami command, which uses the script standard input, standard output, and standard error. The argument of the system function is generally whatever we'd normally type at the shell. For example, if we need to see all Perl scripts in the current directory we need to execute list command like this: ls -l *.pl. Thus, the argument of the system function would be:
system "ls -l *.pl";The examples before obviously inherited the script's STDOUT (since we could see their's output), the following example show that the child process also inherits the STDIN:
print "Now print several lines and press ^D to see your lines sorted:\n"; system "sort";
The system operator may also be invoked with more than one argument, in which case a shell doesn't get involved. That is, special characters like *, |, <, > stay the same and don't get interpreted by the shell. For example, compare
system "sort < wc.pl";and
system "sort", "< wc.pl";In both cases we start the sort program, but in the first example shell redirects the standard input of the program and it reads from file wc.pl. In the second example we hide the special symbol < from the shell and the sort program is trying to open file "< wc.pl".
The return value of the system function is actually an exit status of the child process. In Unix/Linux, an exit value 0 usually means that everything is OK, and a non-zero exit value usually indicates that something went wrong:
unless( system "date" ){
print "Is the current date/time\n";
}
exec "date"; print "We tried to print the date\n";
$date = "date"; my $now = `$date`; print "Time now is: $now";When we placed date in backquotes, Perl executes date command, arranging the standard output to be captured as a string value, and in this case assigned to the $now variable.
If the output from a command has multiple lines, the scalar use of backquotes returns it as a single long string containing newline characters, However, using the same backquoted string in a list context yields a list containing one line of output per element:
@files = `ls *.pl`;
chomp @files;
foreach ( @files ){
if( ! -d ){
printf "%12s %8d\n", "$_", -s;
}
}
The code above gets the names of all Perl script in the current directory and prints them back together with the size.