SPUG:April Meeting: Perl for UNIX Users

SPUG-list-owner tim at consultix-inc.com
Thu Apr 10 17:54:49 CDT 2003


On Thu, Apr 10, 2003 at 06:14:11PM -0400, Asim Jalis wrote:
> On Thu, Apr 10, 2003 at 01:36:41PM -0700, Tim Maher wrote:
> > SPUGsters, We had two speakers tentatively lined up for this
> > month's meeting, but both have elected to postpone until May
> > (too distracted by Wars and Taxes, I guess).  So I'm stepping
> > into the breach, in order to practice some conference talks and
> > get valuable feedback from the SPUGizens.
> 
> Perl has several solutions to the tax problem. What about war?
> Does Perl have any modules that could be used in the war?
> 
> Asim

The use of the four-argument form of substr() comes to mind.
It has the capability of demolishing vital resources with very
little effort (or awareness) on the part of the programmer.

Consider, for example, my favorite (accidental) invocation of this
"feature":

	$_=join '', 'a' .. 'z' ;

	print substr $_, 0, 20, "\n";	# show first chars of string
	print "\n";	# Funny, why's this needed?
	print "'$_'\n";

The output of course is:
	abcdefghijklmnopqrst
	'
	uvwxyz'

The "\n", as the inadvertent 4th argument to substr(), tells Perl
to *replace* the indicated substring [0..19] by the "\n".  This bites
me a few times a year, and I usually waste time testing other parts
of a complex program for far too long before finding it. 

My advice is to resist the temptation to change
	print substr $_, 0, 20;	
into
	print substr $_, 0, 20,"\n";

In fact, I advise newbies as a general rule to always add the "\n"
with a separate call to print(), or by using the -l invocation option;
this approach skirts lots of parenthesis-related issues.

The cure for the above example is of course to tell the compiler where
substr's argument list ends, using parentheses:

	print substr ($_, 0, 20), "\n";	# show first chars of string

Anyway, to get back to the Asim's Saddamical theme:

	$_="Saddam prevents Iraqi freedom!";
	print "$_\n";
	$save=sprintf substr $_, 0, 16, "\n";	# store first chars of string
	print "\U$_\n";

Output:
	Saddam prevents Iraqi freedom!

	IRAQI FREEDOM!

I hereby offer this example of a WMD (Weapon of Mass Destruction)
as a WMI (Weapon of Mass Instruction).

-Tim
*------------------------------------------------------------*
|  Tim Maher (206) 781-UNIX  (866) DOC-PERL  (866) DOC-UNIX  |
|  CEO, JAWCAR ("Just Another White Camel Award Recipient")  |
|  tim at Consultix-Inc.Com  TeachMeUnix.Com  TeachMePerl.Com   |
*+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-*
|  Watch for my  Book: "Minimal Perl for Shell Programmers"  |
*------------------------------------------------------------*



More information about the spug-list mailing list