Welcome to Linux Forums! With a comprehensive Linux Forum, information on various types of Linux software and many Linux Reviews articles, we have all the knowledge you need a click away, or accessible via our knowledgeable members.
Find the answer to your Linux question:
Site Navigation
Linux Forums
Linux Articles
Product Showcase
Linux Downloads
Linux Hosting
Free Magazines
Job Board
IRC Chat
RSS Feeds
Free Publications

In the previous lesson we learnt about string comparisons and fileparsing. In this lesson we'll see how Perl can interact with thefilesystem and execute commands in the Linux operating system. We'llthen use what we've learnt to write a little script.

Executing system commands

Perl provides a function called "system" which canexecute a command or a set of commands directly on the operatingsystem. In fact, Perl passes the command to the operating system, whichexecutes it, and then returns the result back to Perl.

So, for instance, the following Perl script prints the content of the current directory:



What actually happens is that the Unix process which runs the Perlinterpreter forks and the newly created child Unix process executes the"ls" command. When the execution finishes, it returns theexit code of the command back to the Perl interpreter.

If you are familiar with Unix commands exit codes you can test thesuccess of the execution of your command by assigning the return valueof "system" to a variable, and then evaluate this variable.For instance:

$lsExecutedSuccessfully = system("ls");

Here, if "ls" executes successfully, the variable$lsExecutedSuccessfully receives the value 0. This value corresponds tothe successful exit code of the command "ls".

Executing system commands and capturing the output

Sometimes, when you run a Linux command from your Perl script you'remore interested in what it writes on the screen than in its exit code.For instance, when you execute "ls" you're more likely tobe interested in the list of files being printed on the screen than inthe value 0 returned by "system".

To achieve this, you can use evaluated quotes "`"instead of "system". Not only does it executes the command,but it also returns what the commands writes in its standard output:

@files = `ls`;

In this example, the listing of the files returned by"ls" does not appear on the screen. Instead, it gets storedin the @files array.

Changing the working directory

In the shell you would type "cd /home" to change the workingdirectory to /home. You could write the following in your Perl script:

system("cd /home");

But it would have no effect. In fact, since the system call forksfrom the process used by the interpreter, it doesn't change the workingdirectory of your script. Instead, you can use a Perl function called"chdir":

chdir "/home";

Interacting with the filesystem

Perl provides a lot of functions to interact with the files anddirectories of your filesystem. Here are some of these handy functions:


"chmod" changes the permissions of a file or a list of files andreturns the number of files that were changed. The first argument mustbe the numerical mode. Examples:

chmod 0777, "/home/clem/program.pl";

chmod 0777, @myFiles;


"symlink" creates a symbolic link. It is the equivalent of "ln -s".The first argument is the file name, the second argument is the linkname. Example:

symlink "/home/clem/program.pl", "/usr/bin/program";


"mkdir" creates a directory. The first argument is the name of thedirectory and the second argument is the octal mode which defines thepermissions for that directory. For example:

mkdir "/home/clem/perl_programs", 0664;


"rename" is the equivalent of "mv" in Unix. It renames or moves a file. Example:

rename "/home/clem/program.pl", "/home/clem/program";


"rmdir" deletes a directory, but only if it is empty. Example:

rmdir "/home/clem/perl_programs";


"stat" returns a 13-element array which represent the properties of a file. The elements of the array are :

0: $dev, 1: $ino, 2: $mode, 3: $nlink, 4: $uid, 5: $gid, 6: $rdev,7: $size, 8: $atime, 9: $mtime, 10: $ctime, 11: $blksize, 12: $blocks


stat "/home/clem/program.pl";


"unlink" deletes a file or a list of files. Example:

unlink "/home/clem/program.pl";

Perl Script Exercise: Netswitch

In this exercise, we want to be able to switch between networks. Wedefined network configuration files in a directory called "networks".

For instance, here is the content of ./networks/home:




And here is the content of ./networks/work:





The following Perl script takes a network name as its command lineargument, opens the file with the same name from ./networks and setsthe network interface with the data taken from the content of that file:


#default values







$proxy_port = "none";

#gather information from the network file

$network = $1;

$networkFile = "./networks/$network";

open (NETWORK, "$networkFile") or die "$networkFile not found or not readablen";

while ($line = ) {

chomp $line;

($variable, $value) = split /=/, $line;

if ($variable eq "interface") $interface = $value;

elsif ($variable eq "type") $type = $value;

elsif ($variable eq "address") $address = $value;

elsif ($variable eq "gateway") $gateway = $value;

elsif ($variable eq "dns") $dns = $value;

elsif ($variable eq "proxy") $proxy = $value;

elsif ($variable eq "proxy_port") $proxy_port = $value;


#make sure the type and interface are defined

if ($interface eq "none") die "Interface name not definedn";

if ($type eq "none") die "Network type (dhcp, static) not definen";

if ($type eq "dhcp") {

print "Network type: dhcpn";

#just get an IP address and settings from the DHCP Server



elsif ($type eq "static") {

print "Network type: staticn";

#bring the interface up

if ($address eq "none") die ("IP address not definedn");

system("ifconfig $interface $address up");

if ($gateway ne "none") {

print "Gateway: $gatewayn";

system("route add default gw $gateway");


if ($dns ne "none") {

print "DNS Server: $dnsn";

$strNameServer = "cat "."'"."nameserver $dns"."' > /etc/resolv.conf";




else die "Bad network type : $type. Use dhcp or static.n";

Try to understand each line of that script. The script doesn't setthe proxy in APT, Firefox...etc. See if you can update the script toadd such functionality. Also, it would be great if the script couldlist the possible networks available when the user types "netswitch-l". As there are many ways to solve a problem, especially in Perl,please post your solutions and ideas. Together you should be able towrite a great network switcher.

You now know all you need to start writing this script, however if you have any questions do not hesitate to ask.

Lesson 4

Rate This Article: poor excellent
Comments about this article
Where're 2 & 4?
writen by: ClarkePeters on 2006-10-15 05:02:26
Great tutorials. Without any Perl experience I wrote code to read, filter, and sort a huge dictionary that I'd been wanting to reformat for years--all from the instructions from your site. I came back here because I forgot some things, but, unfortunately, lessons 2 and 4 seem to have disappeared. :(
RE: Where're 2 & 4? written by ClarkePeters:
Found 2&4
writen by: ClarkePeters on 2006-10-15 08:08:37
Not sure what's up, but I couldn't get to the even numbered lessons from the odd-numbered lesson links and vice -versa. AT any rate, I just clicked on your name at "Contributed by" and got to all your posts and there were the missing lessons. Great Tutorials! I was glad to get to the other lessons. (I'm using firefox on Ubuntu Linux, not sure why the links wouldn't work. Keep up the good work. :)
RE: Found 2&4 written by ClarkePeters:
QA Engineer
writen by: Jutta Kullmann on 2006-11-01 21:41:12
I am new to learning Perl and was hoping to get all the 10 Lessons, but I only can find 1 - 5. Are there more Lessons or will there be more Lessons? I think they are great!! Thank you.
RE: QA Engineer written by Jutta Kullmann:
writen by: Vanessa on 2006-11-21 06:38:04
RE: Herby written by Vanessa:
writen by: Mark Daher on 2006-12-07 06:04:12
RE: Lessons written by Mark Daher:
writen by: dovee on 2006-12-20 12:30:13
RE: sysadmin written by dovee:
writen by: pushpal on 2007-04-24 06:13:17
i am new to PERL and the tutorials hav helped me in understanding it in a simple way :) i cant find the lessons 6-10. arent they available, or yet to b prepared? looking forward for the rest of the lessons...
RE: gr8!! written by pushpal:
lessons 7-10 missing
writen by: Madhura Veeraiah on 2007-08-27 03:17:21
Hi Am ne wto perl. Lessons are easy and simple. Unfortunately. I could find lesson 1-6. Is lessons 7-10 are unavailable. Are they yet to be prepared
RE: lessons 7-10 missing written by Madhura Veeraiah:
remaining lessons are missing
writen by: vijay on 2007-09-26 11:21:36
please any one let me know the remaining lessons link
RE: remaining lessons are missing written by vijay:
Lesson's 6-10 are missing
writen by: Sanjeev on 2008-01-22 02:41:39
Hi, It was gr8 to learn Perl from this site. I was actually generating a lot of interest and would have been more than obliged if I would have finished all the 10 lessons as it is mentioned in the heading. But to my dismay, I cannot still find the remaining lessons. Few people have found lesson 6 but I have been unfortunate in that. Could you please give me the exact date by which the remaining lessons will be available. Also can you forward me the link for lesson 6.
RE: Lesson's 6-10 are missing written by Sanjeev:
RE: Lesson's 6-10 are missing
writen by: jan1005 on 2010-03-18 01:50:56
Hi Sanjeev, I am not able to find the lessons 6-10. If you know where I could find please let me know.

I like these lessons very much as they kept it very simple and very easy to learn.

Thanks in advance for your reply.
Reply to jan1005:
Web programmer - intermediate
writen by: Bob on 2008-04-23 12:32:02
RE: Web programmer - intermediate written by Bob:
lesson 6-10 r missing
writen by: haritha on 2008-11-14 04:32:59
RE: lesson 6-10 r missing written by haritha:
RE: lesson 6-10 r missing
writen by: jan1005 on 2010-03-18 01:49:34
Hi Haritha, I couldn't find lessons 6-10. Could you please let me know where I could find these. The course is very easy to learn and I mostly like it because they keep it simple.

Thanks for your reply.
Reply to jan1005:
writen by: Crowface on 2009-03-23 07:11:14
without even typing this in, is this wrong? [quote]$network = $1;[/quote] shouldn't it be $network = $ARGV[0];
RE: written by Crowface:
Lession 6-10 are missing
writen by: sujatapatne on 2009-12-20 02:41:35
RE: Lession 6-10 are missing written by sujatapatne:
Lesson 6 link
writen by: jedsch on 2010-07-22 15:15:11
RE: Lesson 6 link written by jedsch:

Comment title: * please do not put your response text here