Softpanorama

May the source be with you, but remember the KISS principle ;-)
Contents Bulletin Scripting in shell and Perl Network troubleshooting History Humor

Softpanorama Bulletin
Vol 21, No. 04 (December, 2009)

Bulletin 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007
2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018

Perl Programming Environment

The key components of programming environment for a programming language are

Perl interpreter

The key part of Perl programming environment is Perl interpreter and the set of modules that constitute Perl standard library. Perl comes in a "batteries included" fashion and has a rick set of standard libraries. As this is a book for Unix system administrators, they have no problems of installing or updating Perl on Unix. We will use version 5.10 but version 5.12 and 5.14 are essentially better debugged version of 5.10 and can be used too. Actually all enterprise versions of Unix and Linux have Perl preinstalled. Also many enterprise applications such as Oracle, HP DataProtector are supplied with Perl interpreter.

To get a version of Perl interpreter you need to type

$ perl -v

This is perl, v5.10.0 built for x86_64-linux-thread-multi

Copyright 1987-2007, Larry Wall

Perl may be copied only under the terms of either the Artistic License or the
GNU General Public License, which may be found in the Perl 5 source kit.

Complete documentation for Perl, including FAQ lists, should be found on
this system using "man perl" or "perldoc perl".  If you have access to the
Internet, point your browser at http://www.perl.org/, the Perl Home Page.

But it make sense briefly discuss installation and Perl programming environment on Windows as this is a standard desktop in enterprise environment. 

One can get Windows version of Perl interpreter either from Cygwin (where is part of the package) or as a standalone package from Active State (www.activestate.com). There are two ways to install it:

Installation of Active Perl on Windows

First, Install ActivePerl. The current (as of August 2012) version is 5.12. But any version starting with 5.10 is OK. 

To run your Perl scripts, type:

Perl <scriptname>

at the command prompt, where <scriptname> is the name of the script you want to launch. Also, if you are using Windows NT and have associated the extension of the file with Perl, typing <scriptname> will also launch the script.

Sample Script

In the /eg directory of your Perl install there is a sample script named example.pl To run it, launch a console window, make the /eg directory your current working directory and type:

You should see:

If you do, you've successfully installed ActivePerl! If not, there's something wrong with your install. Check to make sure that your Path environment variable includes the directories to which you installed the Perl for Win32 core binaries. (You can type set at the command prompt to see what's in your Path.) If you chose the defaults during the install, these should be set to the correct values for you when you start a new command prompt.

One last note, typing Perl -h will display all of the available command line options available to you.

Checking if the installation is successful

Please note that there are two simple ways to check if you installation finished successfully. The first is to run a test script as recommended above, the second is to invoke Perl with -h or -v (show version) options from the DOS prompt. For example:

perl -v

ActiveState also produce GUI-based Perl debugger -- a trial version is available.  This is really good debugger but you can survive with built-in Perl debugger as well. The latter has an advantage of being available on both Windows and Unix.

After the installation you will not see a Perl icon in the Start menu. ActivePerl folder will contains only link to documentation. That's normal as Perl is a command line tool.  After installation please browse Perlwin32faq - Perl for Win32 Frequently Asked Questions -- you will not understand much, but just seeing the tittles you can later return to the relevant part of the FAQ.

That can save you a lot of time.  Here is what How do I install the Perl for Win32 package  part of FAQ states:

How do I install the Perl for Win32 package?

Simply double-click the archive you downloaded, and you will be guided through the installation process by the installation wizard. You can select the parts of the Perl package you want installed, and the location you want to install them to.

Here is a link to additional information about installation ActivePerl Install Notes

Links to some useful documentation are in ActivePerl Help

Installation of Cygwin

Cygwin is a free software package that provides a Unix-like environment and software tool set in Windows environment (2000/XP/Vista). Which is extremely important for creating a proper Perl environment it provides all the necessary classic Unix utilities that you can invoke from scripts.   Installation is based on special downloadable from the WEB installation program. You need to select Perl, VIM, GVIM to get the configuration that can serve you as poor man IDE.

Cygwin contains:

Cygwin consists of a Unix system call emulation library, cygwin1.dll, together with a set of GNU and other free software applications organized into a large number of optionally installed packages. Among these packages are  a complete X11 development toolkit, GNU Emacs, TeX and LaTeX, OpenSSH (client and server), and much more.

Due to presence of emulation layer Cygwin (and especially Cygwin/X) is much slower then X servers which use native Win32 API.

Cygwin is not  equivalent of a VMWare player and does not provide a means for running Linux binary executables under MS-Windows. In order to run such software using Cygwin, that software must be compiled from its sources. Cygwin provides all of the components needed to do this in most cases; most POSIX-compliant software, including X11 applications, can easily be ported to MS-Windows using Cygwin.

Cygwin provides POSIX view of the Windows file system space. The slash ('/') directory points to the system partition (C:) by default. In addition to selecting the slash partition, it allows mounting arbitrary Win32 paths into the POSIX file system space using mount command

mount [OPTION] [<win32path> <posixpath>]

Many people mount each drive letter under the slash partition (e.g. C:\ to /c, D:\ to /d, etc...). that is simpler that /cygdrive/c, /cygdrive/d, etc). Here is additional information about options of the mount command in Cygwin:
 

  -b, --binary     (default)    text files are equivalent to binary files  (newline = \n)
  -c, --change-cygdrive-prefix  change the cygdrive path prefix to <posixpath>
  -f, --force                   force mount, don't warn about missing mount   point directories
  -h, --help                    output usage information and exit
  -m, --mount-commands          write mount commands to replicate user and system mount points and cygdrive prefixes
  -o, --options X[,X...]        specify mount options
  -p, --show-cygdrive-prefix    show user and/or system cygdrive path prefix
  -s, --system     (default)    add system-wide mount point
  -t, --text                    text files get \r\n line endings
  -u, --user                    add user-only mount point
  -v, --version                 output version information and exit
  -x, --executable              treat all files under mount point as executables
  -E, --no-executable           treat all files under mount point as non-executables
  -X, --Cygwin-executable       treat all files under mount point as Cygwin executables

Path translations can be done by executing the cygpath utility program

Usage: cygpath (-d|-m|-u|-w|-t TYPE) [-f FILE] [OPTION]... NAME...
       cygpath [-c HANDLE] 
       cygpath [-ADHOPSW] 
       cygpath [-F ID] 
Convert Unix and Windows format paths, or output system path information

Output type options:
  -d, --dos             print DOS (short) form of NAMEs (C:\PROGRA~1\)
  -m, --mixed           like --windows, but with regular slashes (C:/WINNT)
  -M, --mode            report on mode of file (currently binmode or textmode)
  -u, --unix            (default) print Unix form of NAMEs (/cygdrive/c/winnt)
  -w, --windows         print Windows form of NAMEs (C:\WINNT)
  -t, --type TYPE       print TYPE form: 'dos', 'mixed', 'unix', or 'windows'
Path conversion options:
  -a, --absolute        output absolute path
  -l, --long-name       print Windows long form of NAMEs (with -w, -m only)
  -p, --path            NAME is a PATH list (i.e., '/bin:/usr/bin')
  -s, --short-name      print DOS (short) form of NAMEs (with -w, -m only)
System information:
  -A, --allusers        use `All Users' instead of current user for -D, -P
  -D, --desktop         output `Desktop' directory and exit
  -H, --homeroot        output `Profiles' directory (home root) and exit
  -O, --mydocs          output `My Documents' directory and exit
  -P, --smprograms      output Start Menu `Programs' directory and exit
  -S, --sysdir          output system directory and exit
  -W, --windir          output `Windows' directory and exit
  -F, --folder ID       output special folder with numeric ID and exit
Other options:
  -f, --file FILE       read FILE for input; use - to read from STDIN
  -o, --option          read options from FILE as well (for use with --file)
  -c, --close HANDLE    close HANDLE (for use in captured process)
  -i, --ignore          ignore missing argument
  -h, --help            output usage information and exit
  -v, --version         output version information and exit

The cygpath program is a utility that converts Windows native filenames to Cygwin POSIX-style pathnames and vice versa. It can be used when a Cygwin program needs to pass a file name to a native Windows program, or expects to get a file name from a native Windows program. Alternatively, cygpath can output information about the location of important system directories in either format.

The -u and -w options indicate whether you want a conversion to UNIX (POSIX) format (-u) or to Windows format (-w). Use the -d to get DOS-style (8.3) file and path names. The -m option will output Windows-style format but with forward slashes instead of backslashes. This option is especially useful in shell scripts, which use backslashes as an escape character.

In combination with the -w option, you can use the -l and -s options to use normal (long) or DOS-style (short) form. The -d option is identical to -w and -s together.

Caveat: The -l option does not work if the check_case parameter of CYGWIN is set to strict, since Cygwin is not able to match any Windows short path in this mode.

The -p option means that you want to convert a path-style string rather than a single filename. For example, the PATH environment variable is semicolon-delimited in Windows, but colon-delimited in UNIX. By giving -p you are instructing cygpath to convert between these formats.

The -i option suppresses the print out of the usage message if no filename argument was given. It can be used in make file rules converting variables that may be omitted to a proper format. Note that cygpath output may contain spaces (C:\Program Files) so should be enclosed in quotes.

Example 3.5. Example cygpath usage

#!/bin/sh
if [ "${1}" = "" ];
	then
		XPATH=".";
	else
		XPATH="$(cygpath -w "${1}")";
fi
explorer $XPATH &

The capital options -D, -H, -P, -S, and -W output directories used by Windows that are not the same on all systems, for example -S might output C:\WINNT\SYSTEM32 or C:\WINDOWS\SYSTEM. The -H shows the Windows profiles directory that can be used as root of home. The -A option forces use of the "All Users" directories instead of the current user for the -D, -O and -P options. The -F outputs other special folders specified by their internal numeric code (decimal or 0xhex). For valid codes and symbolic names, see the CSIDL_* definitions in the include file /usr/include/w32api/shlobj.h from package w32api. The current valid range of codes for folders is 0 (Desktop) to 59 (CDBurn area). On Win9x systems with only a single user, -A has no effect; -D and -AD would have the same output. By default the output is in UNIX (POSIX) format; use the -w or -d options to get other formats.

Win32 file systems are case preserving but case insensitive. Cygwin does not currently support case distinction because, in practice, few UNIX programs actually rely on it.

Symbolic links are emulated by files containing a magic cookie followed by the path to which the link points. They are marked with the System attribute so that only files with that attribute have to be read to determine whether or not the file is a symbolic link. Hard links are fully supported under Windows NT on NTFS file systems.

The inode number for a file is calculated by hashing its full Win32 path. The inode number generated by the stat call always matches the one returned in d_ino of the dirent structure. It is worth noting that the number produced by this method is not guaranteed to be unique. However, we have not found this to be a significant problem because of the low probability of generating a duplicate inode number.

Cygwin provides the following functionality for WIN32 applications:
Process control and management:
While processes can be created using the fork(2) function. With the exec family of functions, an existing process can be overlaid with another process. Each process has a unique process id and each process belongs to a process group.
File descriptor semantics:
Open files, pipes, sockets, fifos, and character and block special devices files have file descriptors associated with them. They can be duped and inherited with UNIX semantics.
UNIX signal semantics:
Nearly all of the UNIX signals are provided, including job control signals so that  shell can stop and restart jobs. A process can catch, block or ignore signals. Signals can be sent to processes or to process groups.
Support for devices:
Cygwin provides character and block devices with major and minor numbers as found on UNIX systems.
Terminal interface for consoles, sockets, and serial lines:
The POSIX termios interface is supported for consoles with vt100 emulation. Serial lines, and sockets that have been designated as virtual terminals. Cygwin supports pseudo-ttys.
Use of the mouse with console windows:
The left mouse button in a console window can be used to select text and copy to the clipboard. The right button (or middle button on a three button mouse) can be used to paste text from the clipboard.
Pathname mapping from UNIX to Windows:
 
UNIX naming conventions:
The PATH variable is a : separated list of directories rather than a ; separated list. The cc command generates files with a .o suffix by default. However, some characters such as \, *, ?, |, &, <. >, and : are not valid as part of file names. By default, directories are mounted without case distinction. However, the mount command allows directories to be mounted as case sensitive so that the files makefile and Makefile are distinct. In addition, there is a registry key that can be set to make the default case sensitive.
Mapping to and from UNIX ids/permissions to NT/2000/XP permissions:
Windows NT/2000/XP subject identifiers are mapped to UNIX user ids and group ids. UNIX permissions are mapped onto Windows NT/2000/XP file ACLs. The Administrator can use chown() to change the owner and or group of a file.
File control locking:
UNIX file control advisory locking is supported by Cygwin with deadlock detection.
System V IPC:
The System V semaphore and message calls are implemented.
Runtime linking of dynamically linked libraries:
The dlopen(), dlsym() interface from System V Release 4 is provided.
Error mapping from Windows to UNIX:
Errors returned by WIN32 functions are mapped into UNIX errors.
i-node numbers:
An i-node number is returned when reading a file and when stating a file.
Hard links:
Hard links are supported on NTFS  file system.
Symbolic links:
Symbolic links to files and directories can be created in Cygwin and are implemented as Windows shortcuts. A .lnk suffix will be appended to these file names but will not appear when reading directories with Cygwin. Shortcuts created by Windows appear as symbolic links in Cygwin but do not have the .lnk suffix removed.
Fifo's:
Fifo's (UNIX named pipes) can be created with mkfifo() and opened as an ordinary file.
Setuid and setgid programs:
Users can authorize setuid and/or setgid programs to be run on their behalf and use chmod() to turn on setuid permission for a program. The program must be on an NTFS file system.
inet Daemons and commands:
Cygwin comes with the inet daemon, the telnet daemon, the rlogin daemon, rsh and ssh daemons. It also includes the telnet, ftp, rsh, and rlogin programs.
ssh and ssh daemon:
A compilation of openssh-3.6p1.

Installation of Teraterm

Teraterm  is a reasonably good enough replacement for “cmd” and can serve as  "out of the box" terminal for Cygwin. If you follow press Alt-G in Teraterm,  you’ll get a terminal with the following advantages:

The teraterm.ini file contains all the configuration settings and parameters used by the application. You may modify the file directly in editor. or through the executable (teraterm.exe) by changing settings then saving the configuration via the Setup --> Save Setup... menu.

IDE

Active State offers Komodo IDE for $295 for individual users. It has 21 days trial period so you can see yourself if it worth the money. I think that company money are OK, as for personal money your mileage may vary ;-). Komodo also has a very useful Regex-tool, ppm install GUI, can integrate with versioning software and do FTP. Although I didn't try the recent versions myself, I worked with older version for several years and GUI debugging proved to be a useful capability. Built-in editor is weaker that standalone editors although it has some nice featured, see below.

Komodo editor can be used as "mini IDE" and is free.  It has some interesting features like the ability to run script on any selection from the editing buffer in best vi style. See s more full description below.

VIM and GVIM

One possible "poor man IDE" is VIM and, especially GVIM. Vim is not as great as specialized IDS but still you can achieve quite a lot by careful customarization.  VIM provides syntax highlighting coding for Perl. The most important thing to learn are first additional  ctags.

Vim has the following important features:

When using tags it is nice to have two windows split horizontally. Vim supports both vertical and horizontal window splitting. To split current window horizontally execute “:split” while in the normal mode. To split current window vertically, use “:vsplit” instead. If you don’t provide any filename as argument to split/vsplit then current filename is used. You further split resulting windows as much as you like. Use Ctrl-w w to cycle through the windows. “:close” will close the current windows. “:only” will close all windows except the current one.

Vim provides  facilities for reconciling differences between two “vimdiff main.pl main2.pl” (or “vim -d main.pl main2.pl“) from the command line to see difference made to file main.pl in file main2.pl.

Vim will show both files in vertical split window mode. When you will scroll in one window, Vim will automatically scroll another window for you. You can patch the individual differences using do and dp commands. do will get the patch from the neighbor window and apply it to the current buffer, while dp will apply the difference from the current buffer to the neighbor window. If you need more information on this topic, read file /usr/share/doc/vim-common-6.1/docs/diff.txt.

Here is an excellent article of Leonid Mamchenkov Vim for Perl developers (May.10, 2004). Although written more then 5 years ago it is still the best intro into VIM facilities for Perl users. Below is an abbreviated version with some updates:

Text wrapping

As you code, sometimes text flows further than the width of the editor window. Some people like long lines to be wrapped (in other words, continued on the other line), while others prefer them unwrapped. You can configure Vim to behave according to your liking by adding “set wrap” or “set nowrap” to your .vimrc configuration file.

Flexible tabs

Tabulation is one of the hottest topics in programmers discussions when it comes to style. A very nice explanation of what is the problem with tabulations and spaces can be read at http://www.jwz.org/doc/tabs-vs-spaces.html. I must say though, that I don’t agree with author’s position on the subject. The article does provide you with several options for vi/Vim configuration to control the behavior of the tabs. I will just add/repeat the ones I consider important.

If you need more information on this topic, read file /usr/share/doc/vim-common-6.1/docs/indent.txt.

Line numbering

While Vim always displays your current position in the status line, you might also want to see all lines numbered. To do that, you will need to add “set number” to your .vimrc.

If you need more information on this topic, read file /usr/share/doc/vim-common-6.1/docs/usr_03.txt.

Syntax highlighting

The first thing any developer will notice in Vim is excellent syntax highlighting. All popular languages are supported. Syntax files for less popular are available from Vim web site. Perl is supported out of the box.

Vim identifies keywords, comments, variables, strings, in-line POD and other standard parts of the program and highlights them. Vim supports two color modes: one for terminals with dark background color and another one for terminals with light background color. You can control these modes by specifying command “set bg=dark” and “set bg=light” in your .vimrc.

If you still don’t like the appearance of the code, stay tuned until “Color schemes” discussion.

If you need more information on this topic, read file /usr/share/doc/vim-common-6.1/docs/syntax.txt.

Text completion

One of Vim’s features I cannot live without is text completion. When editing, press Ctrl-n / Ctrl-p to cycle through the current word completion suggestions. Vim generates suggest list based on the words in the current file. If you need key completion to make suggestions from other files, then Vim by default understand the ctags file. Simply run “ctags *.p?” to generate ctags for all Perl files and modules in the current directory (assuming you are using “.pl” extension for Perl scripts and “.pm” extension for Perl modules). This Vim’s feature not only saves a tonne of time on typing, but greatly decreases the error rate, especially with long variable and procedure names in the code.

If you need more information on this topic, read file /usr/share/doc/vim-common-6.1/docs/usr_24.txt.

File Completion

While you are in the command mode, Vim can complete the names of files and directories in case you want to open or save a file. In order to complete a file or a directory name you should start typing it’s name on the command prompt and then press the completion key. You can change the completion key to be almost anything you want with “set wildchar=” line in your .vimrc file.

Window splitting

Sometimes I need to see two or more files simultaneously. While I can always start another Vim session in a separate terminal, it is not as comfortable at times as Vim’s window splitting feature.

Vim supports both vertical and horizontal window splitting. To split current window horizontally execute “:split” while in the normal mode. To split current window vertically, use “:vsplit” instead. If you don’t provide any filename as argument to split/vsplit then current filename is used. You further split resulting windows as much as you like. Use Ctrl-w w to cycle through the windows. “:close” will close the current windows. “:only” will close all windows except the current one.

If you need more information on this topic, read file /usr/share/doc/vim-common-6.1/docs/usr_08.txt.

Diff mode

Vim provides excellent facilities for checking and editing differences between two or more files. Execute “vimdiff main.pl main2.pl” (or “vim -d main.pl main2.pl“) from the command line to see difference made to file main.pl in file main2.pl.

Vim will show both files in vertical split window mode. When you will scroll in one window, Vim will automatically scroll another window for you. You can patch the individual differences using do and dp commands. do will get the patch from the neighbor window and apply it to the current buffer, while dp will apply the difference from the current buffer to the neighbor window.

If you need more information on this topic, read file /usr/share/doc/vim-common-6.1/docs/diff.txt.

Text folding

Yet another popular feature found in popular editors and IDEs is text folding. I think that folding is easier shown then explained. Vim supports six folding methods: by indent, by expression, by syntax, by changes in the text, by marker, and manual folding. For the sake of the example, I will show how to configure folding by marker.

In order to tell Vim to use folding by marker add the following lines to your .vimrc:

" Folding configuration
set foldmethod=marker
" Edit and uncomment next line if you want non-default marker
"set foldmarker="{{{,}}}"

If you need more information on this topic, read files /usr/share/doc/vim-common-6.1/docs/usr_28.txt and /usr/share/doc/vim-common-6.1/docs/fold.txt.

Marks

One of Vim’s features that speeds up navigation is – marks. You can set a mark anywhere in the text and then quickly jump back to it. You can set several marks. You can set marks in several files and then quickly switch between them. I find myself set mark on the place I am currently working at with mc (m is for “mark”, c I use for “current”) and then quickly returning to the same place with 'c.

If you need more information on this topic, read file /usr/share/doc/vim-common-6.1/docs/motion.txt.

Vertical Indent Display

For some people indenting text horizontally is not enough. They need some kind of vertical indentation to help them see corresponding parts of the code. While I am not one of those people, I’ve seen this feature around so often that I decided to add it codemonkey’s .vimrc.

All you need to do to have vertical indent display with pipe (”|”) character is to add the following two lines to your .vimrc.

" This is for vertical indenting
set list
set listchars=tab:|
" NOTE the space char after last backslash.

“:set list” forces Vim to show hidden characters like tabulations, ends of lines, and ends of files. “:set listchars=tab:| ” asks Vim to show only tab characters and use a pipe (”|”) with a space (” “) to do so, instead of usual “^I” thing that Vim likes to show.

Color schemes

Robert (MetaCosm) downloaded all color schemes and put them into a single archive file which he uploaded back to Vim’s web site (http://www.vim.org/scripts/script.php?script_id=625.).

You will most likely notice that some color schemes do not change much colors in your console vim. That is because they are most probably designed for GUI version of Vim, called gvim.

Try executing “gvim +'colorscheme peachpuff' main.pl” to see how gvim looks with selected color scheme.

Now you can try all those color schemes one by one with “:colorscheme something” and choose the one you like best. When you are done choosing, add line “colorscheme something” to your .vimrc.

If you need more information on this topic, read file /usr/share/doc/vim-common-6.1/docs/usr_06.txt.

Block commenting

It is an often need to comment or uncomment blocks of code during the development cycle. While there is a way to do it in Vim without any additional configuration, I try to make life as easy as possible and install the BlockComment plug-in by Chris Russell.

Let’s download BlockComment.vim from http://www.vim.org/scripts/script.php?script_id=473 and copy it into .vim/plugin/ directory. This plug-in automatically provides us with two mappings: “.c” for commenting code and “.C” for uncommenting code back.

File and buffer browser

Vim supports editing of several files simultaneously. One can start Vim as “vim main.pl main2.pl” and then use “:next” and “:previous” to navigate through open files (called “buffers”). It is also possible to open files for editing without quiting Vim every time. For that, one should use simple “:e main2.pl” command, where main2.pl is the name of needed file.

There are, as usual, better (more convenient) ways to work with files and buffers. Vim website lists few plug-ins which can handle only files, or only buffers, or both at the same time. One of those plug-ins is winmanager by Srinath Avadhanula. Let’s grab winmanager from http://www.vim.org/scripts/script.php?script_id=95.

Vim’s winmanager plug-in can make use of bufexplorer plug-in by jeff lanzarotta availalbe from http://www.vim.org/scripts/script.php?script_id=42.

Installation is as usual – saving, unziping, and dos2unixing. Since we don’t want to always have file/directory browser turned on, lets add a mapping line to our .vimrc to “:WMToggle” by F2.

" This is for winmanager
map <F2> :WMToggle<CR>

If you need more information on this topic, read file /usr/share/doc/vim-common-6.1/docs/usr_23.txt.

Tag explorer

If you ask me, I am almost happy. The last thing that I am missing is something that will ease up my code browsing. I need a fast way of switching between different parts of my code and hierarchical view of it. Once again I go fishing to Vim web site and get myself a nice looking taglist plug-in by Yegappan Lakshmanan from http://www.vim.org/scripts/script.php?script_id=273. This one is not even an archive! You just need to copy it into your .vim/plug-in directory. Let’s map “:Tlist” command to F3 key.

" This is for taglist
map <F3> :Tlist<CR>

One annoying thing that I find about taglist is that it resizes the terminal window when possible. I prefer to switch this feature off by add modifying my .vimrc in the following way.

" This is for taglist
let Tlist_Inc_Winwidth = 0
map <F3> :Tlist<CR>

If you need more information on this topic, read file /usr/share/doc/vim-common-6.1/docs/tagsrch.txt.

Perl syntax checking

..copy perl.vim (developed by Lukas Zapletal) into your .vim/compiler/ directory. Now we need to specify for which files we want Vim to use our new perl compiler scripts. This is easily done by adding the following lines to .vimrc.

" Use perl compiler for all *.pl and *.pm files.
autocmd BufNewFile,BufRead *.p? compiler perl

Now you can use “:make” to check your code for errors. If you do have problems in your code, then Vim will position the cursor on the line with the first problem. You can use “:cnext” and “:cprevious” to go through other error messages. “:clist” will show a list of all errors.

If you need more information on this topic, read file /usr/share/doc/vim-common-6.1/docs/usr_30.txt.

 You can also check perl syntax in VIM on each save

au BufWritePost *.pl,*.pm !perl -c %

With this macro every time you save a .pl or .pm file, it executes perl -c and shows you the output.

Perldoc integration

Yet another feature provided in most IDEs is on-line documentation. Vim helps developers even with that. By default, Vim comes with system manual support on all UNIX boxes. This comes very handy when you use system commands in your scripts and need to check command line parameters. Just position the cursor on the word that you are interested in and press K. Vim will execute “man word“, where “word” is the word under the cursor. This is helpful but not as much as we need it.

Let’s visit Vim site again and download Perldoc plug-in (developed by Colin Keith) from http://www.vim.org/scripts/script.php?script_id=209. unzip perldoc.zip and run all extracted files through dos2unix. It’s a good idea to add a F1 mapping to “:Perldoc” in your .vimrc.

" This is for perldoc.vim
autocmd BufNewFile,BufRead *.p? map <F1> :Perldoc<cword><CR>
autocmd BufNewFile,BufRead *.p? setf perl
autocmd BufNewFile,BufRead *.p? let g:perldoc_program='/usr/bin/perldoc'
autocmd BufNewFile,BufRead *.p? source /home/codemonkey/.vim/ftplugin/perl_doc.vim

If you are using a newer version then I do, then you skip the last line.

Now, whenever you hit F1 while in the perl file, “:Perldoc” will get executed for the word that you have under the cursor, your current window will split horizontally and you’ll see appropriate perldoc page.

After installation of this plug-in I have noticed that syntax highlighting in few of my programs broke. After a quick look, I understood that that happened because of my extensive usage of underscore (”_”) character in procedure names. I had to fix it by simply adding underscore (”_”) character to the list of keyword characters on line 14 in file .vim/ftplugin/perl_doc.vim.

" Adds / and . as used in requires.
" setlocal iskeyword=a-z,A-Z,48-57,:,/,.
" Adds / and . as used in requires. Also adds _ as used in procedure names.
setlocal iskeyword=a-z,A-Z,48-57,:,/,.,_

Komodo Editor

Komodo editor does not have built-in macro language but other then that it is a average editor

The key features include:

DzSoft Perl Editor

DzSoft Perl Editor ($49) is a good editor for Perl. It has built-in debugging features, a simple editor with syntax highlighting, a syntax check feature that finds errors in your script. Here is the list of features from the site:

Notepad++

Notepad++ is a free simple editor which provides Perl syntax highlighting and basic editing features. I use it personally and its OK for small scripts. For larger scripts you need more full-fledged editor like SlickEditor.

Perl Debugger

Perl has built-in debugger but neither classic Cygwin not ActiveState distributions provide an IDE for Perl. I already mentioned VIM/GVIm as a possibility for Cygwin, but this is not a perfect solution. It just has an important advantage of synergy with standard Unix environment. Two viable free options are Komodo from active state (editor is free, but IDE is not) and Eclipse. 

Eclipse with EPIC plugin is probably the most powerful among free IDE. It supports Perl debugger. It also supports code snippets. Try Preferences->Perl EPIC->Templates. It's heavy-weight solution and you need a powerful dual core CPU on you desktop or laptop and plenty of memory to use it.

Perl beautifiers

Perl has one good beautifier (perltidy). Also Code2HTML  can convert a program source code to syntax highlighted HTML.

Lint and XREF table generators

List of variables used in the program only once is produced if you compile Perl with options -cw, for example:

perl -cw sample

Perl interpreter can produce cross reference table of all variables used. Here is what authors of Programming Perl wrote about rarely used capability:

18.6. Code Development Tools

The O module has many interesting Modi Operandi beyond feeding the exasperatingly experimental code generators. By providing relatively painless access to the Perl compiler's output, this module makes it easy to build other tools that need to know everything about a Perl program.

The B::Lint module is named after lint(1), the C program verifier. It inspects programs for questionable constructs that often trip up beginners but don't normally trigger warnings. Call the module directly:

perl -MO=Lint,all myprog
Only a few checks are currently defined, such as using an array in an implicit scalar context, relying on default variables, and accessing another package's (nominally private) identifiers that start with _. See B::Lint(3) for details.

The B::Xref module generates cross-reference listings of the declaration and use of all variables (both global and lexically scoped), subroutines, and formats in a program, broken down by file and subroutine. Call the module this way:

perl -MO=Xref myprog > myprof.pxref
For instance, here's a partial report:
Subroutine parse_argv
  Package (lexical)
    $on               i113, 114
    $opt              i113, 114
    %getopt_cfg       i107, 113
    @cfg_args         i112, 114, 116, 116
  Package Getopt::Long
    $ignorecase       101
    &GetOptions       &124
  Package main
    $Options          123, 124, 141, 150, 165, 169
    %$Options         141, 150, 165, 169
    &check_read       &167
    @ARGV             121, 157, 157, 162, 166, 166
This shows that the parse_argv subroutine had four lexical variables of its own; it also accessed global identifiers from both the main package and from Getopt::Long. The numbers are the lines where that item was used: a leading i indicates that the item was first introduced at the following line number, and a leading & means a subroutine was called there. Dereferences are listed separately, which is why both $Options and %$Options are shown.

The B::Deparse is a pretty printer that can demystify Perl code and help you understand what transformations the optimizer has taken with your code. For example, this shows what defaults Perl uses for various constructs:

% perl -MO=Deparse -ne 'for (1 .. 10) { print if -t }'
LINE: while (defined($_ = <ARGV>)) {
    foreach $_ (1 .. 10) {
        print $_ if -t STDIN;
    }
}
The -p switch adds parentheses so you can see Perl's idea of precedence:
% perl -MO=Deparse,-p -e 'print $a ** 3 + sqrt(2) / 10 ** -2 ** $c'
print((($a ** 3) + (1.4142135623731 / (10 ** (-(2 ** $c))))));
You can use -q to see what primitives interpolated strings are compiled into:
% perl -MO=Deparse,-q -e '"A $name and some @ARGV\n"'
'A ' . $name . ' and some ' . join($", @ARGV) . "\n";
And this shows how Perl really compiles a three-part for loop into a while loop:
% perl -MO=Deparse -e 'for ($i=0;$i<10;$i++) { $x++ }'
$i = 0;
while ($i < 10) {
    ++$x;
}
continue {
    ++$i
}
You could even call B::Deparse on a Perl bytecode file produced by perlcc -b, and have it decompile that binary file for you. Perl opcodes may be a tough read, but when necessary it can be helpful.

Apache 1.3

Apache 1.3 is adequate for Perl development and faster then Apache 2.x. Installation with Cygwin is straightforward -- you just need to select it.

Prev | Up | Contents | Down | Next



Etc

FAIR USE NOTICE This site contains copyrighted material the use of which has not always been specifically authorized by the copyright owner. We are making such material available in our efforts to advance understanding of environmental, political, human rights, economic, democracy, scientific, and social justice issues, etc. We believe this constitutes a 'fair use' of any such copyrighted material as provided for in section 107 of the US Copyright Law. In accordance with Title 17 U.S.C. Section 107, the material on this site is distributed without profit exclusivly for research and educational purposes.   If you wish to use copyrighted material from this site for purposes of your own that go beyond 'fair use', you must obtain permission from the copyright owner. 

ABUSE: IPs or network segments from which we detect a stream of probes might be blocked for no less then 90 days. Multiple types of probes increase this period.  

Society

Groupthink : Two Party System as Polyarchy : Corruption of Regulators : Bureaucracies : Understanding Micromanagers and Control Freaks : Toxic Managers :   Harvard Mafia : Diplomatic Communication : Surviving a Bad Performance Review : Insufficient Retirement Funds as Immanent Problem of Neoliberal Regime : PseudoScience : Who Rules America : Neoliberalism  : The Iron Law of Oligarchy : Libertarian Philosophy

Quotes

War and Peace : Skeptical Finance : John Kenneth Galbraith :Talleyrand : Oscar Wilde : Otto Von Bismarck : Keynes : George Carlin : Skeptics : Propaganda  : SE quotes : Language Design and Programming Quotes : Random IT-related quotesSomerset Maugham : Marcus Aurelius : Kurt Vonnegut : Eric Hoffer : Winston Churchill : Napoleon Bonaparte : Ambrose BierceBernard Shaw : Mark Twain Quotes

Bulletin:

Vol 25, No.12 (December, 2013) Rational Fools vs. Efficient Crooks The efficient markets hypothesis : Political Skeptic Bulletin, 2013 : Unemployment Bulletin, 2010 :  Vol 23, No.10 (October, 2011) An observation about corporate security departments : Slightly Skeptical Euromaydan Chronicles, June 2014 : Greenspan legacy bulletin, 2008 : Vol 25, No.10 (October, 2013) Cryptolocker Trojan (Win32/Crilock.A) : Vol 25, No.08 (August, 2013) Cloud providers as intelligence collection hubs : Financial Humor Bulletin, 2010 : Inequality Bulletin, 2009 : Financial Humor Bulletin, 2008 : Copyleft Problems Bulletin, 2004 : Financial Humor Bulletin, 2011 : Energy Bulletin, 2010 : Malware Protection Bulletin, 2010 : Vol 26, No.1 (January, 2013) Object-Oriented Cult : Political Skeptic Bulletin, 2011 : Vol 23, No.11 (November, 2011) Softpanorama classification of sysadmin horror stories : Vol 25, No.05 (May, 2013) Corporate bullshit as a communication method  : Vol 25, No.06 (June, 2013) A Note on the Relationship of Brooks Law and Conway Law

History:

Fifty glorious years (1950-2000): the triumph of the US computer engineering : Donald Knuth : TAoCP and its Influence of Computer Science : Richard Stallman : Linus Torvalds  : Larry Wall  : John K. Ousterhout : CTSS : Multix OS Unix History : Unix shell history : VI editor : History of pipes concept : Solaris : MS DOSProgramming Languages History : PL/1 : Simula 67 : C : History of GCC developmentScripting Languages : Perl history   : OS History : Mail : DNS : SSH : CPU Instruction Sets : SPARC systems 1987-2006 : Norton Commander : Norton Utilities : Norton Ghost : Frontpage history : Malware Defense History : GNU Screen : OSS early history

Classic books:

The Peter Principle : Parkinson Law : 1984 : The Mythical Man-MonthHow to Solve It by George Polya : The Art of Computer Programming : The Elements of Programming Style : The Unix Hater’s Handbook : The Jargon file : The True Believer : Programming Pearls : The Good Soldier Svejk : The Power Elite

Most popular humor pages:

Manifest of the Softpanorama IT Slacker Society : Ten Commandments of the IT Slackers Society : Computer Humor Collection : BSD Logo Story : The Cuckoo's Egg : IT Slang : C++ Humor : ARE YOU A BBS ADDICT? : The Perl Purity Test : Object oriented programmers of all nations : Financial Humor : Financial Humor Bulletin, 2008 : Financial Humor Bulletin, 2010 : The Most Comprehensive Collection of Editor-related Humor : Programming Language Humor : Goldman Sachs related humor : Greenspan humor : C Humor : Scripting Humor : Real Programmers Humor : Web Humor : GPL-related Humor : OFM Humor : Politically Incorrect Humor : IDS Humor : "Linux Sucks" Humor : Russian Musical Humor : Best Russian Programmer Humor : Microsoft plans to buy Catholic Church : Richard Stallman Related Humor : Admin Humor : Perl-related Humor : Linus Torvalds Related humor : PseudoScience Related Humor : Networking Humor : Shell Humor : Financial Humor Bulletin, 2011 : Financial Humor Bulletin, 2012 : Financial Humor Bulletin, 2013 : Java Humor : Software Engineering Humor : Sun Solaris Related Humor : Education Humor : IBM Humor : Assembler-related Humor : VIM Humor : Computer Viruses Humor : Bright tomorrow is rescheduled to a day after tomorrow : Classic Computer Humor

The Last but not Least


Copyright © 1996-2016 by Dr. Nikolai Bezroukov. www.softpanorama.org was created as a service to the UN Sustainable Development Networking Programme (SDNP) in the author free time. This document is an industrial compilation designed and created exclusively for educational use and is distributed under the Softpanorama Content License.

The site uses AdSense so you need to be aware of Google privacy policy. You you do not want to be tracked by Google please disable Javascript for this site. This site is perfectly usable without Javascript.

Original materials copyright belong to respective owners. Quotes are made for educational purposes only in compliance with the fair use doctrine.

FAIR USE NOTICE This site contains copyrighted material the use of which has not always been specifically authorized by the copyright owner. We are making such material available to advance understanding of computer science, IT technology, economic, scientific, and social issues. We believe this constitutes a 'fair use' of any such copyrighted material as provided by section 107 of the US Copyright Law according to which such material can be distributed without profit exclusively for research and educational purposes.

This is a Spartan WHYFF (We Help You For Free) site written by people for whom English is not a native language. Grammar and spelling errors should be expected. The site contain some broken links as it develops like a living tree...

You can use PayPal to make a contribution, supporting development of this site and speed up access. In case softpanorama.org is down you can use the at softpanorama.info

Disclaimer:

The statements, views and opinions presented on this web page are those of the author (or referenced source) and are not endorsed by, nor do they necessarily reflect, the opinions of the author present and former employers, SDNP or any other organization the author may be associated with. We do not warrant the correctness of the information provided or its fitness for any purpose.

Last modified: October 11, 2015