20 Killer Perl Programming Tips for Beginners on UNIX / Linux OS
1. List all Installed Perl Modules from Unix Command Line
$ perl -MFile::Find=find -MFile::Spec::Functions -Tlw -e 'find { wanted => sub { print canonpath $_ if /\.pm\z/ }, no_chdir => 1 }, @INC'
- File::Find and File::Spec::Functions module are used to list all installed modules.
- -M option loads the module. It executes use module before executing the script
- -T option enables taint checking, which instructs perl to keep track of data from the user and avoid doing anything insecure with it. Here this option is used to avoid taking the current directory name from the @INC variable and listing the available .pm files from the directory recursively.
- -l option enables automatic line-ending processing in the output. Print statements will have the new line separator (\n) added at the end of each line.
- -w option prints any warning messages.
- -e option indicates that the following string is to be interpreted as a perl script (i.e., sequence of commands).
2. List all Installed Perl Modules from a perl script (Using ExtUtils::Installed package)
my $Inst = ExtUtils::Installed->new();
my @Modules = $Inst->modules();
print "Current List of Installed PERL Modules:\n\n";
foreach my $mod(@Modules){
print "$mod\n";
}
Note: The module ExtUtils::Installed is not pre-installed with perl program. So you should install it from cpan.
3. List Perl Modules Using Perldoc Command
perldoc perlmodlib lists all the modules that comes pre-installed with the perl program
Note: You can also use ‘perldoc perllocal’ command to identify additional perl modules that are installed.
$ perldoc perllocal
perldoc perllocal command lists all optional modules installed in the system with the following information:
- Installation date
- Directory location of where the perl module is installed
- Perl Module version number
- etc.,
4. View Perl Documentation From Unix Command Line
You can use either perldoc or man command to get help about a particular perl module as shown below.
$ perldoc Regexp::Common (or) $ man Regexp::Common
If the perl document is not enough, use perldoc option -m, to view both source code and unformatted pod documentation of the specified perl module.
$ perldoc -m Regexp::Common
To view documentation on a specific perl function, use the option -f, as shown below.
$ perldoc -f splice
5. View Online Perl Documentation (or Download it for Offline Use)
Lot of excellent perl tutorials are available online at Perl programming documentation.
From this website, you can also download the HTML or PDF version of the perl documentation for offline viewing.
- Full version (contains HTML and PDF files) – perldoc.tar.gz
- Lite version (contains HTML files only) – perldoc-html.tar.gz
6. Read Perl Documentation Using Podbrowser
Download the podbrowser. You can browse the installed perl modules, functions, and perl documentation visually from the podbrowser. From their website:
PodBrowser is a documentation browser for Perl. You can view, search and print documentation for Perl's builtin functions, its "perldoc" pages, pragmatic modules and the default and user-installed modules.
Note: You can also use Vim editor as Perl-IDE as we discussed earlier.
7. Modify CPAN Module Configuration Manually
To install the perl modules from Linux command line, use CPAN. We discussed earlier about how to install perl modules — both manually and using CPAN command.
The first time you use the Perl module CPAN ( perl -MCPAN ), a script is executed to configure several options. For example, it configures the location of tar, gzip and unzip files, the cache size for the build directory, source file location etc.,
To reconfigure CPAN module configuration files manually you can edit one of the following files.
- ~/.cpan/CPAN/MyConfig.pm – User specific Perl CPAN Configuration file
- /etc/perl/CPAN/Config.pm – System-wide Perl CPAN Configuration file is stored somewhere in the perl module directory tree.
$ vim ~/.cpan/CPAN/MyConfig.pm (and / or) $ vim /etc/perl/CPAN/Config.pm
8. Modify CPAN Module Configurations Interactively
Launch the cpan shell as shown below and execute o conf init, which will ask “are you ready for manual configure”, give your option ( Yes / No ) to continue. This will list all the configuration parameters along with it’s value.
$ perl -MCPAN -e shell cpan> o conf init cpan> o conf
9. Verify if a Perl Module is Installed
If you like to know whether a perl module (for example, Regexp::Common) is installed, execute the following command. If you get “1″ as the output, then the specified perl module is installed. If not, you’ll get the error message as shown below.
$ perl -MRegexp::Common -le 'print 1'
Can't locate Regexp/Common.pm in @INC (@INC contains: /etc/perl /usr/local/lib/perl/5.8.8 /usr/local/share/perl/5.8.8 /usr/lib/perl5 /usr/share/perl5 /usr/lib/perl/5.8 /usr/share/perl/5.8 /usr/local/lib/site_perl .).
Note: You can also check if perl module is installed using perldoc or man command. If the perl module is installed the manual page of the module will open successfully. If not, it will say “no manual / documentation found for this module”
$ perldoc Regexp::Common $ man Regexp::Common
10. List the Directories Where Perl Modules are Located
The perl array @INC contains the list of places that the ‘do EXPR’, ‘require’, or ‘use’ constructs look for their library files. The following one-liner shows the contents of the @INC perl array:
$ perl -e 'foreach $folder (@INC) { print "$folder\n";}'
11. Check the Version of an Installed Perl Module
To check the version number of a module use the following command.
#-- check the version number of CGI module $ perl -MCGI -e 'print "$CGI::VERSION \n"' #-- check the version number of Regexp::Common module $ perl -MRegexp::Common -e 'print "$Regexp::Common::VERSION \n"'
Note: Also, make sure to read our review about the Perl Best Practices book.
12. Specify the Minimum Perl Module Version to Use
Sometimes you might want to use a specific version of a perl module in your program. To avoid using earlier version of that module, append the minimum version number you want in the use ‘module’ statement as shown below.
#-- Use version 5.8 of later of module LWP use LWP 5.8
Note: Your perl program will exit with an appropriate error message if the installed module version is lower than the version you specified in the use command.
13. Useful Perl Modules to Develop Web Applications
If you are developing web application, you might want to consider using the following perl modules.
- CGI – General purpose module for creating web pages
- Template – Template Toolkit to generating dynamic web content
- LWP – LWP is used to fetch web contents
- WWW::Mechanize – Use this to automate interaction with a website
14. Determine the Operating System the Perl Script is Running Under
The name of the underlying operating system is stored in the variable $^O. Following are some of the common $^O value
- linux – Linux
- MSWin32 – Windows
- aix – AIX
- solaris – Solaris
Note: The value stored in $^O contains only the name of the operating system, not the release number. To determine the release number, consider using POSIX::uname() from POSIX package.
15. Define Constant Values Inside Perl Script
The best way to define constant values is to use Perl Readonly or Constant module as shown below.
use Readonly; Readonly my $PI => 3.1415926535; (or) use Constant PI => 3.1415926535;
Please note the following:
- Using Readonly module you can define Readonly scalars, hashes and arrays.
- If you try to modify a Readonly variable, the program will die.
16. Determine the OS User and/or OS Group Running a Perl Script
Use the following predefined variables to get the user and group information of 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
Please note the following:
- 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).
17. Executing External Commands
There are many ways to execute external commands from Perl as explained below.
- 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 perl script
18. Parse Plain Messy Perl Script Using B::Deparse
Got a chunk of obfuscated or just plain messy and hard to read Perl code? The B::Deparse module may be able to help. It compiles, then decompiles the program it is given, expanding it out and formatting it nicely. It removes the comment lines written in the perl program.
To run it at the command line, type “perl -MO=Deparse prog.pl”. Here is an example of its usage,
First create the input program:
$ cat scary.pl for(74,117,115,116){$::a.=chr};(($_.='qwertyui')&& (tr/yuiqwert/her anot/))for($::b);for($::c){$_.=$^X; /(p.{2}l)/;$_=$1}$::b=~/(..)$/;print("$::a$::b $::c hack$1.");
Pass the perl script scary.pl to the Deparse module
$ perl -MO=Deparse scary.pl foreach $_ (74, 117, 115, 116) { $a .= chr $_; } ; $_ .= 'qwertyui' and tr/eiqrtuwy/nr oteah/ foreach ($b); foreach $_ ($c) { $_ .= $^X; /(p.{2}l)/; $_ = $1; } $b =~ /(..)$/; print "$a$b $c hack$1."; scary.pl syntax OK
19. List Installed DBI Drivers
DBI is the standard database interface module for Perl. The following Perl program prints a list of all installed DBI drivers.
use strict; use warnings; use DBI; print map "$_\n",DBI->available_drivers;
Example output of the above program:
DBM ExampleP File Proxy Sponge mysql
If the driver you require is not installed, use CPAN to find the right DBD (database driver) module.
20. Regular expression special variable
One of the most useful feature or the most powerful string manipulation facility in perl is regular expression.
At heart of this is the regular expression which is shared by many other UNIX utilities.
Perl has a host of special variables that get filled after every m// or s/// regex match.
- $1, $2, $3, etc. hold the backreferences.
- $+ holds the last (highest-numbered) backreference.
- $& (dollar ampersand) holds the entire regex match.
- $’ (dollar followed by an apostrophe or single quote) holds the part of the string after (to the right of) the regex match.
- $` (dollar backtick) holds the part of the string before (to the left of) the regex match.
Using these variables is not recommended in perl scripts when performance matters, as it causes Perl to slow down all regex matches in your entire perl script.
All these variables are read-only, and persist until the next regex match is attempted.
Example
$string = "This is the geek stuff article for perl learner";
$string =~ /the (g.*) stuff(.*) /;
print "Matched String=>{1}\nBefore Match=>
\nAfter Match=>
\nLast Paren=>{1}\nFirst Paren=>$1\n";
Output of the above example :
Matched String=>the geek stuff article for perl Before Match=>This is After Match=>learner Last Paren=> article for perl First Paren=>geek
相關文章
- java-string-tutorial-and-examples-beginners-programmingJava
- Unix、Windows、Mac OS、Linux系統故事WindowsMacLinux
- 掌握Linux,OS X,Unix的Shell環境Linux
- Windows、Linux、Unix、Mac OS X系統哪個更好用?WindowsLinuxMac
- Shell入門:掌握Linux,OS X,Unix的Shell環境Linux
- Programming Java 2 Micro Edition for Symbian OSJava
- oom killerOOM
- 理解和配置 Linux 下的 OOM KillerLinuxOOM
- 使用Perl自動化UNIX系統管理(轉)
- Linux TipsLinux
- Advanced Programming in the UNIX Environment, 3rd Edition出版
- Mac OS X Programming讀書筆記4 - WindowsMac筆記Windows
- Oracle Database on Unix AIX,HP-UX,Linux,Mac OS X,Solaris,Tru64 Unix Operating Systems Installation aOracleDatabaseAILinuxMac
- The Omnipotent Monster Killer
- Postgres Basic Commands for Beginners
- Linux sed TipsLinux
- 20個 Unix/Linux 命令技巧薦Linux
- Spring MVC for beginners 筆記SpringMVC筆記
- Mac OS X Programming讀書筆記5 - ControlsMac筆記
- D. The Omnipotent Monster Killer
- Perl中本地時間和UNIX時間戳間相互轉換時間戳
- Linux核心引數overcommit_memory和OOM killer介紹LinuxMITOOM
- 工具推薦. 線上unix, 線上python/perl指令碼測試環境Python指令碼
- Unix, Linux 和MacOSLinuxMac
- LINUX UNIX建立組Linux
- linux/unix find命令Linux
- Linux/Unix Errno CodeLinux
- linux/unix程式設計手冊-16_20Linux程式設計
- Linux的一些TipsLinux
- Linux + OS RedHat AS 5LinuxRedhat
- linux os 監控Linux
- MVC Controller Dependency Injection for Beginners【翻譯】MVCController
- Linux的一些Tips(轉)Linux
- Linux 與 Unix 之差異Linux
- fstatat()函式 Unix/Linux函式Linux
- linux/unix命令參考Linux
- Linux和UNIX監控Linux
- Linux/Unix筆記本Linux筆記