<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>UseStrict Consulting &#187; perl crash course</title>
	<atom:link href="http://usestrict.net/tag/perl-crash-course/feed/" rel="self" type="application/rss+xml" />
	<link>http://usestrict.net</link>
	<description>Professional IT Solutions &#38; Training</description>
	<lastBuildDate>Sat, 12 May 2012 14:25:42 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>Perl Crash Course: Pragmas, Perl Modules, and CPAN</title>
		<link>http://usestrict.net/2009/05/perl-crash-course-pragmas-perl-modules-and-cpan/</link>
		<comments>http://usestrict.net/2009/05/perl-crash-course-pragmas-perl-modules-and-cpan/#comments</comments>
		<pubDate>Sun, 24 May 2009 01:00:14 +0000</pubDate>
		<dc:creator>vinny</dc:creator>
				<category><![CDATA[Perl]]></category>
		<category><![CDATA[CPAN]]></category>
		<category><![CDATA[modules]]></category>
		<category><![CDATA[Perl Course Howto]]></category>
		<category><![CDATA[perl crash course]]></category>
		<category><![CDATA[pragmas]]></category>

		<guid isPermaLink="false">http://usestrict.net/?p=475</guid>
		<description><![CDATA[About Perl Pragmas, Modules, and CPAN - the Comprehensive Perl Archive Network.]]></description>
			<content:encoded><![CDATA[<p>I always like to say that 90% of Perl is its modules. Back in 2000 when I was working as a junior Perl programmer I was asked to write a web application that, among other things, could send contact messages through email. Unfortunately, I never had anyone to really teach me the Path of Perl &#8211; I only relied on Learning Perl by Randall Schwartz, and whatever I could find on the net. I had a really hard time with that application, mainly because I didn&#8217;t know about Perl modules, MySQL and SQL language. Had I been familiar with at least the Perl modules part, I wouldn&#8217;t have had to spend 8 days and nights in the office (including my birthday). I didn&#8217;t even know how to <tt>use strict;</tt> at the time! Keep reading if <tt>use strict;</tt> makes no sense to you.</p>
<p>Being the extensible and flexible language that it is, Perl provides us with some safeguards and helpers to assist in avoiding what happened to me (I wish I knew that back then). The first of which I&#8217;ll talk about is Pragmas.<br />
<span id="more-475"></span></p>
<h2>Pragmas</h2>
<p>Pragmas are special modules that come installed by default in every Perl distribution. They tell the interpreter of how it is supposed to act. To turn them on, all you have to do is call the special word <tt>use</tt> with the appropriate Pragma. To turn them off, call <tt>no</tt> and the Pragma in question. The most common and powerful Pragma is, in my opinion, <tt>strict</tt> (hence the name of this blog: <tt>use strict;#)</tt>).</p>
<p>Strict tells the Perl interpreter that all variables must be declared and tightens up security a notch. To <tt>use strict;</tt> you have to have at least working knowledge of lexical variables. It takes a while to getting used to at first, but once you&#8217;re hooked, you won&#8217;t know how you could possibly have written Perl programs without it before (I know I don&#8217;t).</p>
<pre  class="brush:perl">
#!/usr/bin/perl

$var = 1; # OK
use strict;
$var1 = 2; # compile time error
</pre>
<p><em>example.pl</em></p>
<p>In our example above, Perl will refuse to run, raising a compile time error like such:</p>
<p><strong>Global symbol &#8220;$var1&#8243; requires explicit package name at example.pl line 5.<br />
Execution of example.pl aborted due to compilation errors.</strong></p>
<p>That&#8217;s <tt> strict</tt> in effect. Notice that <tt>$var</tt> was not cited, since <tt>strict</tt> was only enforced below it. In order to bypass that error, we should have declared our variable with either <tt>my</tt>, <tt>our</tt>, or <tt>local</tt> &#8211; depending on the need. <tt>my</tt> is the most common. Look up &#8220;Packages, Namespaces, and Lexical scopes&#8221; for more on those 3 operators.</p>
<pre  class="brush:perl">
#!/usr/bin/perl

$var = 1; # OK
use strict;
my $var1 = 2; # OK
</pre>
<p><tt>use strict;</tt> is so important that it is usually the second line of code in any decent Perl program &#8211; the first line being the <a href="javascript:;" title="shebang - comes from Hash (#) and Bang (!), which are the first 2 characters of the line. Tells *nix systems which program must be used to interpret the contents of the file. Shebang lines are ignored in Windows systems." >shebang</a>.</p>
<p>If you need to turn off <tt>strict</tt> for one reason or another, you can do so with the key word <tt>no</tt>.</p>
<pre  class="brush:perl">
#!/usr/bin/perl

use strict;
my $var = 1; # OK
no strict;
$var1 = 2; # also OK
</pre>
<p>When writing your Perl programs, it&#8217;s also good to turn on <tt>warnings</tt> and <tt>diagnostics</tt>. <tt>warnings</tt> will complain about possible problems such as useless uses of certain functions. <tt>diagnostics</tt>, on the other hand, will throw you a truckload of information regarding errors. It&#8217;s a good place to start when you&#8217;re stumped.</p>
<h2>Perl Modules</h2>
<p>Perl modules are pieces of code or packages that can be imported into your script with the keyword <tt>use</tt> in the same way as Pragmas. They can be Object Oriented, Procedural, or both. I will not discuss how to write a module in this post, but I <em>will</em> tell you where to find them for download and how to install them.</p>
<p>My all time favorite module is <a href="http://search.cpan.org/~ilyam/Data-Dumper-2.121/Dumper.pm" target="_blank">Data::Dumper</a>. So I will use it in the following examples. The funny <tt>::</tt> between Data and Dumper is kind of like a directory separator. The module Dumper resides in the directory Data, found in one of the paths configured in the Perl config files or the PERL5LIB environmental variable (which set the @INC array).</p>
<p>Data::Dumper comes installed by default, along with hundreds other modules that the developers deemed worthy. To test that your Perl distro has it, run the following command in a command line:</p>
<p><code>$ perl -MData::Dumper -e 'print "OKn"'</code></p>
<p>You&#8217;ll most definitely see the <code>OK</code> being printed on your screen. The command passes 2 parameters to the Perl interpreter: <code>-M</code> which tells it to load a module (in this case Data::Dumper &#8211; no spaces between -M and the module name, or you&#8217;ll get a &#8220;missing argument&#8221; error), and <code>-e</code> which tells it to execute a piece of code (we told it to print OK, but any valid piece of code would do).</p>
<p>Look at what would have happened if we tried to load a module that wasn&#8217;t installed:</p>
<p><code>$ perl -Maaaa -e 'print "OKn"'</code><br />
<strong>Can&#8217;t locate aaaa.pm in @INC (@INC contains: /usr/lib/perl5/5.10/i686-cygwin /usr/lib/perl5/5.10 /usr/lib perl5/site_perl/5.10/i686-cygwin /usr/lib/perl5/site_perl/5.10 /usr/lib/perl5/vendor_perl/5.10/i686-cygwin /usr/lib/perl5/vendor_perl/5.10 /usr/lib/perl5/vendor_perl/5.10 /usr/lib/perl5/site_perl/5.8 /usr/lib/perl5/vendor_perl/5.8 .).<br />
BEGIN failed&#8211;compilation aborted.</strong></p>
<p>To install a module, you can do it the hard way or the easy way. Some modules are harder than others, so I&#8217;ll stick with the easier ones for now. Let&#8217;s start with the hard way.</p>
<p>First, you should know where to find your module. <a href="http://www.cpan.org" target="_blank">CPAN &#8211; The Comprehensive Perl Archive Network</a> is the place to go to get your modules. It has a handy <a href="http://search.cpan.org" target="_blank">search engine</a> which will search through almost 16000 modules at the time of this writing (5/2009). There you will find code ranging from the most trivial to the craziest needs. If there&#8217;s one thing that CPANs contributors don&#8217;t lack, it&#8217;s creativity (that&#8217;s a compliment).</p>
<p>Enter a keyword in the search engine and it will list all relative modules. Click on the link to the one that interests you most. You will be shown its documentation in POD (Plain Old Documentation) format. That&#8217;s the data you will most likely need to learn how to use your module. It should also be the most up-to-date information, since it&#8217;s kept by its authors. </p>
<p>At the top of the POD screen, you&#8217;ll see a breadcrumb set of links showing the Author&#8217;s name, the module&#8217;s distribution name and version, and the module name itself:</p>
<p><a href="http://search.cpan.org/~ilyam/" target="_blank">Ilya Martynov</a> &gt;  <a href="http://search.cpan.org/~ilyam/Data-Dumper-2.121/" target="_blank">Data-Dumper-2.121 </a> &gt;  Data::Dumper </p>
<p>Click on the link for the module&#8217;s distribution name and version, to go to the distribution details screen. You will see lots of information about the module and its sub-modules, but what should concern you right now is the download link next to the release name. Click on it and download the module tarball.</p>
<p>Now this is where I halt and tell you that potential headaches lie ahead. There are basically 2 kinds of modules: PurePerl ones and C-based ones. PurePerl modules are just that &#8211; modules that are solely written in Perl. The vast majority of modules, however, are written in C with bindings special for Perl. Those usually have to be compiled and as such, need a C/C++ compiler and a <code>make</code> program. The good news is that most *nix systems come with those tools already installed or readily available. Windows systems, however, require that you install nmake and preferably Microsoft Visual C++. Check out my post about <a href="http://usestrict.net/2009/01/16/perl-installing-mqseries-module-on-windows-xp/" target="_blank">installing MQSeries module on Windows</a> for more information on how to get Microsoft Visual C++</p>
<p>Back to installing the module&#8230;</p>
<p>Unpack your module in some directory where you have full access. I like to keep an untouched copy of the tarball, by reading the gunzipped contents and throwing it to the screen with the <code>-c</code> option, and piping it to tar with <code>xvf -</code> parameters:</p>
<p><code>gunzip -c tarball.tar.gz | tar -xvf -</code></p>
<p>You&#8217;ll end up with a directory having the name of your distribution. Go in there and read all README files you can find. Read the INSTALL files if any.</p>
<p>One of the files you&#8217;ll see in the directory is <code>Makefile.PL</code>. That&#8217;s the kickoff file for the installation. It takes the following optional parameters: PREFIX, LIB, and INC, and creates a <code>makefile</code> tailor made for your system. It&#8217;s important to set the PREFIX parameter if you want the module installed in a place other than the default. LIB and INC point to the C lib and include directories, respectively.</p>
<p>Now that you have your <code>makefile</code>, it&#8217;s just a matter of running <code>make</code>, <code>make test</code>, and finally <code>make install</code>. Depending on the module, you should have no issues whatsoever. Other more &#8220;sensitive&#8221; modules, however, often require hours of work and even some tweaking of the makefiles by hand. <a href="http://search.cpan.org/~pythian/DBD-Oracle-1.23/Oracle.pm">DBD::Oracle</a> is by far the craziest module I&#8217;ve ever had to install. In some machines it&#8217;s a piece of cake, and others it manages to amuse with the amount of errors it pulls out of the hat. Anyway&#8230;</p>
<p>That was the hard way. Now for the easy way.</p>
<h2>CPAN</h2>
<p>If you&#8217;re finding it strange to see the CPAN title here when I&#8217;ve already talked about it above, don&#8217;t worry &#8211; I&#8217;m talking about the application CPAN and not the website.</p>
<p>Perl comes with the CPAN module installed, and most of the time it also creates a script in the bin directory called <code>cpan</code>. It&#8217;s an interactive shell that allows you to fetch information regarding authors and modules, and also allows you to install modules without having to go through the whole process of downloading the distribution, unpacking, etc.</p>
<p>Start up the CPAN application by calling </p>
<p><code>$ perl -MCPAN -e shell</code></p>
<p>If it&#8217;s the very first time you call it, you will be promped to answer a series of questions. Sticking to the default values is almost always OK. One of the first questions you will be asked is if you want CPAN to configure everything automatically. I recommend against it unless you know that the defaults are correct and will enable you to successfully install modules. And if you know that, then you probably already know how to use the CPAN application and this post has nothing new. <img src='http://usestrict.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Once the questions have been answered, you will be presented with a cpan prompt. Type <code>?</code> to know what options you have.</p>
<pre>cpan[1]> ?
Display Information                                                (ver 1.9205)
 command  argument          description
 a,b,d,m  WORD or /REGEXP/  about authors, bundles, distributions, modules
 i        WORD or /REGEXP/  about any of the above
 ls       AUTHOR or GLOB    about files in the author's directory
    (with WORD being a module, bundle or author name or a distribution
    name of the form AUTHOR/DISTRIBUTION)

Download, Test, Make, Install...
 get      download                     clean    make clean
 make     make (implies get)           look     open subshell in dist directory
 test     make test (implies make)     readme   display these README files
 install  make install (implies test)  perldoc  display POD documentation

Upgrade
 r        WORDs or /REGEXP/ or NONE    report updates for some/matching/all modu
les
 upgrade  WORDs or /REGEXP/ or NONE    upgrade some/matching/all modules

Pragmas
 force  CMD    try hard to do command  fforce CMD    try harder
 notest CMD    skip testing

Other
 h,?           display this menu       ! perl-code   eval a perl command
 o conf [opt]  set and query options   q             quit the cpan shell
 reload cpan   load CPAN.pm again      reload index  load newer indices
 autobundle    Snapshot                recent        latest CPAN uploads</pre>
<p>Use <code>o conf</code> to display the parameters to which you answered all those questions. You can change them with <code>o conf</code> as well. If you didn&#8217;t enable auto-commit before, you will have to call <code>o conf commit</code> to save your changes for use in future sessions.</p>
<p><code>o conf http_proxy "http://some_proxy.com:80"</code></p>
<p>The <code>m</code> command allows you to fetch information regarding a certain module.</p>
<pre>cpan[2]> m Data::Dumper
.... Possibly some data about fetching updated files from the internet here ....
Module id = Data::Dumper
    DESCRIPTION  Convert data structure into perl code
    CPAN_USERID  GSAR (Gurusamy Sarathy <gsar@cpan.org>)
    CPAN_VERSION 2.121
    CPAN_FILE    I/IL/ILYAM/Data-Dumper-2.121.tar.gz
    DSLIP_STATUS SdpOp (standard,developer,perl,object-oriented,Standard-Perl)
    MANPAGE      Data::Dumper - stringified perl data structures, suitable for b
oth printing and C<eval>
    INST_FILE    /usr/lib/perl5/5.10/i686-cygwin/Data/Dumper.pm
    INST_VERSION 2.121_14</pre>
<p>In the output above, CPAN tells us that we alreay have Data::Dumper version 2.121_14 installed. If you are not sure what is the exact name of a module, use the <code>i</code> command to fetch information using a regex:</p>
<pre>cpan[3]> i /klingon/
Distribution    JALDHAR/DateTime-Event-Klingon-1.0.1.tar.gz
Distribution    PNE/Lingua-Klingon-Collate-1.03.tar.gz
Distribution    PNE/Lingua-Klingon-Recode-1.02.tar.gz
Distribution    PNE/Lingua-Klingon-Segment-1.03.tar.gz
Module    DateTime::Event::Klingon (JALDHAR/DateTime-Event-Klingon-1.0.1.tar.gz)

Module    Lingua::Klingon::Collate (PNE/Lingua-Klingon-Collate-1.03.tar.gz)
Module    Lingua::Klingon::Recode (PNE/Lingua-Klingon-Recode-1.02.tar.gz)
Module    Lingua::Klingon::Segment (PNE/Lingua-Klingon-Segment-1.03.tar.gz)
8 items found</pre>
<p>Once you&#8217;re happy with the module name, you can check if it&#8217;s installed or not using <code>m</code></p>
<pre>cpan[4]> m Lingua::Klingon::Collate
Module id = Lingua::Klingon::Collate
    CPAN_USERID  PNE (Philip Newton
<pne@cpan.org>)
    CPAN_VERSION 1.03
    CPAN_FILE    P/PN/PNE/Lingua-Klingon-Collate-1.03.tar.gz
    INST_FILE    (not installed)</pre>
<p>Install it with <code>install</code> command.</p>
<p><code>cpan[5] install Lingua::Klingon::Collate</code></p>
<p>Now, unless you already have module Test::Differences installed, Lingua::Klingon::Collate will fail with a dependency error. Not all modules are like that. Some are coded in a way that CPAN actually asks you if you want to follow and install dependencies automagically. Those are a cinch to install.</p>
<p>If something goes wrong, look at the output of the installation. Best case scenario, you&#8217;re just missing another module and it didn&#8217;t warn you about it. For example, after Lingua::Klingon::Collate failed with the warning that I should have Test::Differences installed, I tried to install that dependency directly. It also failed. When looking at the output on the screen, I see a bunch of lines like this:</p>
<pre>
t/regression..........Can't locate Text/Diff.pm in @INC (@INC contains: /home/vi
alves/.cpan/build/Test-Differences-0.4801-lI_xia/blib/lib /home/vialves/.cpan/bu
ild/Test-Differences-0.4801-lI_xia/blib/arch /usr/lib/perl5/5.10/i686-cygwin /us
r/lib/perl5/5.10 /usr/lib/perl5/site_perl/5.10/i686-cygwin /usr/lib/perl5/site_p
erl/5.10 /usr/lib/perl5/vendor_perl/5.10/i686-cygwin /usr/lib/perl5/vendor_perl/
5.10 /usr/lib/perl5/vendor_perl/5.10 /usr/lib/perl5/site_perl/5.8 /usr/lib/perl5
/vendor_perl/5.8 .) at /home/vialves/.cpan/build/Test-Differences-0.4801-lI_xia/
blib/lib/Test/Differences.pm line 213.
</pre>
<p>You&#8217;ll notice that the error is the same as when we did the <code>$ perl -Maaaa -e 'print "OK"'</code>. Module Text/Diff.pm (or namely Text::Diff) is not installed. So we now go on that quest of following dependencies by hand. </p>
<p>It so happens that Test::Differences tried to install Text::Diff, but Text::Diff failed during the test phase. Suppose I know that those failed tests are not important and won&#8217;t hinder the results of the rest (I don&#8217;t, but bare with me), I can force CPAN to disregard the test failures:</p>
<pre>
cpan[6]> force install Text::Diff
Running install for module 'Text::Diff'
Running make for R/RB/RBS/Text-Diff-0.35.tar.gz
  Has already been unwrapped into directory /home/vialves/.cpan/build/Text-Diff-
0.35-B8Qsuo
  Has already been made
Running make test
/usr/bin/perl.exe "-MExtUtils::Command::MM" "-e" "test_harness(0, 'blib/lib', 'b
lib/arch')" t/*.t
t/ext_format......ok
t/general.........Use of /g modifier is meaningless in split at t/general.t line
 129.
Use of /g modifier is meaningless in split at t/general.t line 130.
t/general.........ok
t/inputs..........ok
t/keygen..........ok
t/outputs.........1/8 No such file or directory at t/outputs.t line 12, <SLURP>
line 6.
t/outputs......... Dubious, test returned 2 (wstat 512, 0x200)
 Failed 4/8 subtests
t/table...........ok

Test Summary Report
-------------------
t/outputs.t   (Wstat: 512 Tests: 4 Failed: 0)
  Non-zero exit status: 2
  Parse errors: Bad plan.  You planned 8 tests but ran 4.
Files=6, Tests=29,  1 wallclock secs ( 0.04 usr  0.04 sys +  0.59 cusr  0.26 csy
s =  0.93 CPU)
Result: FAIL
Failed 1/6 test programs. 0/29 subtests failed.
make: *** [test_dynamic] Error 255
  RBS/Text-Diff-0.35.tar.gz
  /usr/bin/make test -- NOT OK
//hint// to see the cpan-testers results for installing this module, try:
  reports RBS/Text-Diff-0.35.tar.gz
Running make install
Installing /usr/lib/perl5/site_perl/5.10/Text/Diff.pm
Installing /usr/lib/perl5/site_perl/5.10/Text/Diff/Table.pm
Writing /usr/lib/perl5/site_perl/5.10/i686-cygwin/auto/Text/Diff/.packlist
Appending installation info to /usr/lib/perl5/5.10/i686-cygwin/perllocal.pod
  RBS/Text-Diff-0.35.tar.gz
  /usr/bin/make install  -- OK
Failed during this command:
 RBS/Text-Diff-0.35.tar.gz                    : make_test FAILED but failure ign
ored because 'force' in effect
</pre>
<p>Now I can go on to installing Text::Differences and finally Lingua::Klingon::Collate.</p>
<pre>cpan[7] install Test::Differences
.... some output here ....
Appending installation info to /usr/lib/perl5/5.10/i686-cygwin/perllocal.pod
  OVID/Test-Differences-0.4801.tar.gz
  /usr/bin/make install  -- OK

cpan[8] install Lingua::Klingon::Collate
Running install for module 'Lingua::Klingon::Collate'
Running Build for P/PN/PNE/Lingua-Klingon-Collate-1.03.tar.gz
  Has already been unwrapped into directory /home/vialves/.cpan/build/Lingua-Kli
ngon-Collate-1.03-MX7FZn
  -- No Build created, won't make
Running Build test
  Make had some problems, won't test
Running Build install
  Make had some problems, won't install</pre>
<p>Ok, that happens. It&#8217;s because of the previous bad attempt. We can bypass that by telling CPAN to restart the build from scratch. To do so, it must first clean the build environment for that module.</p>
<p><code><br />
cpan[9] clean Lingua::Klingon::Collate<br />
</code></p>
<p>That usually does the trick and enables you to run the <code>install</code> again, but if it doesn&#8217;t, you can <code>force get Lingua::Klingon::Collate</code> to get a fresh package.</p>
<pre>
cpan[27]> install Lingua::Klingon::Collate
Running install for module 'Lingua::Klingon::Collate'
Running Build for P/PN/PNE/Lingua-Klingon-Collate-1.03.tar.gz
  Has already been unwrapped into directory /home/vialves/.cpan/build/Lingua-Kli
ngon-Collate-1.03-ZA4a1s

  CPAN.pm: Going to build P/PN/PNE/Lingua-Klingon-Collate-1.03.tar.gz

Checking whether your kit is complete...
Looks good

Checking prerequisites...
Looks good

Creating new 'Build' script for 'Lingua-Klingon-Collate' version '1.03'
Copying lib/Lingua/Klingon/Collate.pm -> blib/lib/Lingua/Klingon/Collate.pm
Manifying blib/lib/Lingua/Klingon/Collate.pm -> blib/libdoc/Lingua.Klingon.Colla
te.3pm
HTMLifying blib/lib/Lingua/Klingon/Collate.pm -> blib/libhtml/site/lib/Lingua/Kl
ingon/Collate.html
./Build: blib/lib/Lingua/Klingon/Collate.pm: cannot resolve L<strcoll(3)> in par
agraph 60.
./Build: blib/lib/Lingua/Klingon/Collate.pm: cannot resolve L<strxfrm(3)> in par
agraph 60.
  PNE/Lingua-Klingon-Collate-1.03.tar.gz
  ./Build -- OK
Running Build test
t/01_base...........ok
t/02_strcoll........ok
t/03_strxfrm........ok
t/04_strunxfrm......ok
t/05_list...........ok
All tests successful.
Files=5, Tests=87,  1 wallclock secs ( 0.05 usr  0.03 sys +  0.52 cusr  0.25 csy
s =  0.85 CPU)
Result: PASS
  PNE/Lingua-Klingon-Collate-1.03.tar.gz
  ./Build test -- OK
Running Build install
Prepending /home/vialves/.cpan/build/Lingua-Klingon-Collate-1.03-ZA4a1s/blib/arc
h /home/vialves/.cpan/build/Lingua-Klingon-Collate-1.03-ZA4a1s/blib/lib to PERL5
LIB for 'install'
Installing /usr/lib/perl5/site_perl/5.10/Lingua/Klingon/Collate.pm
Installing /usr/share/man/man3/Lingua.Klingon.Collate.3pm
Installing /usr/share/doc/perl-5.10.0/html/html3/site/lib/Lingua/Klingon/Collate
.html
Writing /usr/lib/perl5/site_perl/5.10/i686-cygwin/auto/Lingua/Klingon/Collate/.p
acklist
  PNE/Lingua-Klingon-Collate-1.03.tar.gz
  ./Build install  -- OK</pre>
<p>Type <code>q</code> to exit the shell and that&#8217;s it! There are many other options when using CPAN, but what you&#8217;ve seen so far in this post should be enough to get you started. Just remember to use <code>?</code> every now and then to see what powers are offered to you.</p>
]]></content:encoded>
			<wfw:commentRss>http://usestrict.net/2009/05/perl-crash-course-pragmas-perl-modules-and-cpan/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Perl Crash Course: File and Directory Tests and Manipulation</title>
		<link>http://usestrict.net/2009/04/perl-crash-course-file-and-directory-tests-and-manipulation/</link>
		<comments>http://usestrict.net/2009/04/perl-crash-course-file-and-directory-tests-and-manipulation/#comments</comments>
		<pubDate>Wed, 15 Apr 2009 15:15:55 +0000</pubDate>
		<dc:creator>vinny</dc:creator>
				<category><![CDATA[Perl]]></category>
		<category><![CDATA[file and directory manipulation]]></category>
		<category><![CDATA[perl crash course]]></category>

		<guid isPermaLink="false">http://usestrict.net/?p=429</guid>
		<description><![CDATA[Basics on manipulating files and directories with Perl.]]></description>
			<content:encoded><![CDATA[<p><strong>by André Batosti<br />
revision: Vinny alves</strong><br />
<code><br />
</code></p>
<h3>Opening Files</h3>
<p>To read or write files in Perl, you need to open a filehandle. Filehandles in Perl are yet another kind of identifier.<br />
They act as convenient references (handles, if you will) between your program and the operating system about a particular file. They contain information about how the file was opened and how far along you are in reading (or writing) the file. They also contain user-definable attributes about how the file is to be read or written.</p>
<p>To open a new file on system you need to create the <em>filehandle</em> for this file using the command open</p>
<p>	<em><strong>open(filehandle, pathname);</strong></em></p>
<p>The filehandle is the identifier that will describe the file and the pathname &#8211; the full path of the file you trying to open. Typically it is represented by a constant, but when working with complex programs, it is best to use a scalar variable in order to safely pass it from one subroutine or method to another.</p>
<p><span id="more-429"></span></p>
<p>Example:</p>
<pre name="code" class="php">
	open(PASS_FILE, "/etc/passwd"); # equivalent to open(PASS_FILE,"&lt; /etc/passwd");
	# or
	open(my $pass_file, "/etc/passwd");
</pre>
<p><strong>Note:</strong> it&#8217;s always a good idea to test if <tt>open()</tt> worked well:</p>
<pre name="code" class="php">
	open(PASS_FILE,"/etc/passwd") || die("Can't open passwd: $!n"); # $! gives the system error message
</pre>
<p>Any modern version of Perl also accepts the 3 parameter notion, which is safer:</p>
<pre name="code" class="php">
	open(PASS_FILE, "&lt;" , "/etc/passwd");
</pre>
<p>When you done all with the file you need to close then using the command close</p>
<pre name="code" class="php">
        close(PASS_FILE);
</pre>
<h3>Reading Files</h3>
<p>You can read from Perl&#8217;s filehandles in a couple of different ways. The most common method is to use the file input operator, also called the angle (or diamond) operator (&lt;&gt;). To read a filehandle, simply put the filehandle name inside the angle operator and assign the value to a variable:</p>
<pre name="code" class="php">
	open(MYFILE, "myfile");
	$line = &lt;MYFILE&gt;;
</pre>
<p>The angle operator in a scalar context reads one line of input from the file. When called after the entire file has been read, the angle operator returns the value undef.</p>
<p>In array context, the whole file is read and stored in the array &#8211; one line per element;</p>
<h3>Writing Files</h3>
<p>To write data into a file you need to open the filehandle to write. The open command before is for reading only. To open for writing we need to use &#8216;&gt;&#8217; mode to create a new file or overwrite an existing one and &#8216;&gt;&gt;&#8217; mode to append an existing file or create a new one.</p>
<pre name="code" class="php">
	open(NEWFILE, "&gt;newfile"); # overwrites or creates newfile
	open(MYFILE, "&gt;&gt;myfile"); # appends data to myfile
</pre>
<p>After open a file to write you can use the print command with the filehandle:</p>
<pre name="code" class="php">
	print NEWFILE "this goes into newfilen"; # note the lack of commas between print and filehandle
</pre>
<h3>More on Modes</h3>
<p>So far we&#8217;ve seen modes &#8216;&lt;&#8217;, &#8216;&gt;&#8217;, and &#8216;&gt;&gt;&#8217;. There are other modes we can use depending on our needs. Adding a &#8216;+&#8217; before &#8216;&gt;&#8217; or &#8216;&lt;&#8217; (making &#8216;+&gt;&#8217; or &#8216;+&lt;&#8217;) will grant us read AND write access to the file. &#8216;+&gt;&#8217;, however, will truncate your file first.</p>
<p>Perl also allows you to use pipes on your filenames, print to anonymous temporary files, and much much more.<br />
See <a href="http://perldoc.perl.org/functions/open.html" target="_blank">perldoc&#8217;s open</a> for more details.<br />
<code><br />
</code>	</p>
<h3>Special filehandles</h3>
<p>The Perl have some special filehandles that was always open this is for standard input, output and error<br />
They are</p>
<ul>
<li>STDOUT &#8211; The standard output</li>
<li>STDIN &#8211; The standart input</li>
<li>STDERR &#8211; The error standard output</li>
</ul>
<p>You can specify which is your default output handle (the one print sends data to when no filehandle is passed) with<br />
the <tt>select()</tt> function:</p>
<pre name="code" class="php">
	open(FH,"&gt; myfile.txt);
	$old_fh = select(FH); # changes default output and saves original
	print "This goes to myfile.txtn";
	close(FH);
	select($old_fh);
	print "This goes to the screenn";
</pre>
<p><code><br />
</code></p>
<p><code><br />
</code>	</p>
<h3>File test operators</h3>
<p>Before you open a file, sometimes it&#8217;s nice to know whether the file exists, whether the file is really a directory, or whether opening the file will give a permission denied error. If you could examine the file&#8217;s metadata, you could get answers to these questions. For these situations, Perl provides the file test operators. The file test operators all have the following syntax</p>
<p><strong><em>-X filehandle</em></strong></p>
<p>OR</p>
<p><strong><em>-X pathname</em></strong></p>
<p>The valid operators for file tests are:</p>
<ul>
<li><em>-r</em> Returns true if the file is readable</li>
<li><em>-w</em> Returns true if the file is writeable</li>
<li><em>-e</em> Returns true if the file exists</li>
<li><em>-z</em> Returns true if the file exists but is empty</li>
<li><em>-s</em> Returns size of the file in bytes if it exists</li>
<li><em>-f </em>Returns true if the file is a regular file rather than a directory</li>
<li><em>-d</em> Returns true if the file is a directory</li>
<li><em>-T</em> Returns true if the file appears to be a text file</li>
<li><em>-B</em> Returns true if the file appears to be a binary file</li>
<li><em>-M</em> Returns the age (in days) since the file was modified</li>
</ul>
<h3>Working with directories</h3>
<p>The first step in obtaining directory information from your system is to create a directory handle. A directory handle is something like a filehandle, except that instead of a file&#8217;s contents, you read the contents of a directory through the directory handle. To open a directory handle, you use the <tt>opendir()</tt> function:</p>
<pre name="code" class="php">
        opendir(dirhandle, pathname);
</pre>
<p>To get the content of the directory you need to use the <tt>readdir()</tt> function to get the next directory entry or the entire list of files, depending on context (scalar or list, respectively). It returns undef once you reach the end of your list.</p>
<pre name="code" class="php">
	$next_file = readdir(dirhandle);
       # OR
	@files = readdir(dirhandle);
</pre>
<p>After you finish you need to close the directory using the function <tt>closedir()</tt></p>
<pre name="code" class="php">
	closedir(dirhandle);
</pre>
<p>A shortcut to this process is to use file globbing techniques:</p>
<pre name="code" class="php">
	@all_files = &lt;*&gt;; # gets you the listing of all files in the current directory
	@shell_scripts = glob("*.sh"); # safer
</pre>
<h3>Basic directory operations</h3>
<p>If you need to change, create and remove directories you can use the functions <tt>chdir()</tt>, <tt>mkdir</tt> and <tt>rmdir</tt> using this syntax:</p>
<pre name="code" class="php">
	chdir pathname; # to change remote dir
	mkdir pathname; # to create a directory
	rmdir pathname; # to remove the entire directory
</pre>
<h3>Basic file operations</h3>
<p>To remove files you need to use the <tt>unlink()</tt> function and to rename, use <tt>rename()</tt> <img src='http://usestrict.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<pre name="code" class="php">
	unlink list_of_files;
	rename oldname, newname;
</pre>
<h3>The <tt>stat</tt> Function</h3>
<p>If you need to get all information about a file you need to use the <tt>stat()</tt> function.</p>
<p>It returns an array containing the following:</p>
<pre>
0 dev     Device number
1 ino     Inode number
2 mode    File's mode (permissions)
3 nlink   Number of links
4 uid     User ID (UID) of the owner
5 gid     Group ID (GID) of the owner
6 rdev    Special file info
7 size    Size of file in bytes
8 atime   Time of last access
9 mtime   Time of last modification
10 ctime  Inode change time
11 blksz  Disk block size
12 blocks Number of blocks in file
</pre>
<pre name="code" class="php">
        ($dev,  $ino,   $mode,  $nlink, $uid,     $gid,   $rdev,
         $size, $atime, $mtime, $ctime, $blksize, $blocks) = stat(pathname);
</pre>
<p style="text-align:right;"><a href="http://usestrict.net/2009/03/24/perl-crash-course-subroutines/">« Subroutines</a> | <a href="http://usestrict.net/2008/10/05/perl-crash-course/" target="_self">TOC</a> | Some built-in functions for everyday use »</p>
]]></content:encoded>
			<wfw:commentRss>http://usestrict.net/2009/04/perl-crash-course-file-and-directory-tests-and-manipulation/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Perl Crash Course: Basic Regular Expressions</title>
		<link>http://usestrict.net/2009/04/perl-crash-course-basic-regular-expressions/</link>
		<comments>http://usestrict.net/2009/04/perl-crash-course-basic-regular-expressions/#comments</comments>
		<pubDate>Tue, 07 Apr 2009 14:06:43 +0000</pubDate>
		<dc:creator>vinny</dc:creator>
				<category><![CDATA[Perl]]></category>
		<category><![CDATA[crash course]]></category>
		<category><![CDATA[delimiter]]></category>
		<category><![CDATA[derivation]]></category>
		<category><![CDATA[environments]]></category>
		<category><![CDATA[fo]]></category>
		<category><![CDATA[fool]]></category>
		<category><![CDATA[forward slashes]]></category>
		<category><![CDATA[implementation]]></category>
		<category><![CDATA[instances]]></category>
		<category><![CDATA[match]]></category>
		<category><![CDATA[occurrences]]></category>
		<category><![CDATA[Perl Course Howto]]></category>
		<category><![CDATA[perl crash course]]></category>
		<category><![CDATA[posix]]></category>
		<category><![CDATA[quantifier]]></category>
		<category><![CDATA[regular expression syntax]]></category>
		<category><![CDATA[Regular Expressions]]></category>
		<category><![CDATA[replacements]]></category>
		<category><![CDATA[sorry for the inconvenience]]></category>
		<category><![CDATA[string comparisons]]></category>

		<guid isPermaLink="false">http://usestrict.net/?p=384</guid>
		<description><![CDATA[Basic Regular Expressions for Perl]]></description>
			<content:encoded><![CDATA[<p>Coming soon, a revamped version of this article. Sorry for the inconvenience. </p>
<p style="text-align:right;"><a href="http://usestrict.net/2009/02/01/perl-crash-course-gettin-jiggy-wit-it/">« Gettin&#8217; jiggy wit it</a> | <a href="http://usestrict.net/2008/10/05/perl-crash-course/" target="_self">TOC</a> | <a href="http://usestrict.net/2009/04/14/perl-crash-course-control-structures/">Control Structures »</a></p>
]]></content:encoded>
			<wfw:commentRss>http://usestrict.net/2009/04/perl-crash-course-basic-regular-expressions/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Perl Crash Course: Subroutines</title>
		<link>http://usestrict.net/2009/03/perl-crash-course-subroutines/</link>
		<comments>http://usestrict.net/2009/03/perl-crash-course-subroutines/#comments</comments>
		<pubDate>Tue, 24 Mar 2009 23:27:32 +0000</pubDate>
		<dc:creator>vinny</dc:creator>
				<category><![CDATA[Perl]]></category>
		<category><![CDATA[Perl Course Howto]]></category>
		<category><![CDATA[perl crash course]]></category>

		<guid isPermaLink="false">http://usestrict.net/?p=294</guid>
		<description><![CDATA[Introduction Subroutines are user-created functions that execute a block of code at any given place in your program. It is a best practice, however, to aggregate them all either at the beginning or the end the main program. Subroutine declarations initiate with the key word &#8220;sub&#8221; . Conventionally, subroutine names are all lowercase characters sub [...]]]></description>
			<content:encoded><![CDATA[<h3>Introduction</h3>
<p>Subroutines  are user-created functions that execute a block of code at any given place in your program. It is a best practice, however, to aggregate them all either at the beginning or the end the main program.</p>
<p>Subroutine declarations initiate with the key word &#8220;sub&#8221; . Conventionally, subroutine names are all lowercase characters</p>
<p>sub NAME (PROTOTYPE) BLOCK</p>
<pre class="php" name="code">print_hello; <b># subroutine can be executed/called before the actual block is created</b>

sub print_hello {
      print "Hello worldn";
}</pre>
<p>When we called <em>print_hello</em> we told Perl that we wanted the piece of code named print_hello to be executed. The result is a &#8220;Hello World&#8221; showing up on our screen. The only benefit we have from that snippet in its current form is that we won&#8217;t have to copy/paste the print statement all over our script if we want to repeat it. All we need to do is call <em>print_hello</em>;<br />
<span id="more-294"></span><br />
Another, older, but still common form of calling it would be</p>
<pre class="php" name="code">&amp;print_hello;</pre>
<h3>Parameters</h3>
<p>As mentioned before, our previous example doesn&#8217;t do much by itself. The good news is that subroutines can take a list of parameters and do something based on what it receives. Let&#8217;s change our example for something a little better:</p>
<pre class="php" name="code">$me = "Vinny";

print_hello($me);

sub print_hello {
	$name = shift;
	print "Hello $namen";
}

<b># prints out "Hello Vinny"</b></pre>
<p>Let&#8217;s take a closer look at that. During my subroutine call, I&#8217;m passing it a list of 1 element &#8220;Vinny&#8221;.  That element is populated into the special array <tt>@_</tt>, which is then passed into the subroutine. Like <tt>$_</tt>, you don&#8217;t have to explicitly point out <tt>@_</tt> when using certain array functions.  In our example, we <tt>shift</tt>ed the first element of <tt>@_</tt> into our variable <tt>$name</tt> and printed it out.</p>
<p>It would have been possible to work directly against <tt>$_[0]</tt>, yes, but doing so might be dangerous depending on what you&#8217;re doing. Here&#8217;s why: there are 2 ways of passing parameters into a subroutine.</p>
<p>The first and more common is <em>pass-by-value</em>. Pass-by-value is when we use the value of <tt>$_[0]</tt> into a variable of our own declared within the subroutine. Due to the lexical nature of subroutines (<tt>$name</tt> doesn&#8217;t exist outside of the subroutine in our example &#8211; we&#8217;ll see more about that later), the original variable (<tt>$me</tt>) is untouched.</p>
<p>The second and possibly dangerous way of doing it is by using the <em>pass-by-reference</em> method. In this case, we work against <tt>$_[0]</tt> directly, which is a reference to the variable passed. Any changes to<tt> $_[0]</tt> will affect the contents of <tt>$me</tt>. This is typically NOT what you want to do.</p>
<pre class="php" name="code">$me = "Vinny";

print_hello($me);
print "$men";

sub print_hello {
    print "Hello $_[0]n";
    $_[0] .= " Alves";
}</pre>
<p>When passing more complex structures such as hashes and arrays, bear in mind that Perl flattens them out into a single array by default.</p>
<pre class="php" name="code">@myArray = qw(red green blue);

%myHash = ('apple'=&gt;'fruit',  'dog' =&gt;'pet');

print_hello(@myArray,%myHash);

sub print_hello {
	for $i (@_) {
		print "Got $in";
	}
}
<b># Prints :
# red
# green
# blue
# apple
# fruit
# dog
# pet</b></pre>
<p>Again, that&#8217;s probably not what you wanted. To maintain the individuality and structure of your elements, you will need to pass a reference to each element as parameters, and then assign them to variables in your subroutine.</p>
<pre class="php" name="code">
print_hello(@myArray,%myHash);

sub print_hello {

	$array_ref = shift;
	$hash_ref = shift;

	for $fruit (@$array_ref) {
		print "Got $fruitn";
	}

	print "A dog is a " . $hash_ref-&gt;{dog} . "n";
}</pre>
<h3>Returning Data</h3>
<p>Subroutines are handy for returning some sort of data. By default, it returns 0 or 1 if the keyword <tt>return</tt> isn&#8217;t found &#8211; depending on the success or failure of the subroutine. Optionally, you can have it return a specific piece of data, such as a scalar, a list/array or reference to arrays, hashes, scalars, etc. The same rules we find in passing parameters apply to returning data.</p>
<pre name="code" class="php">
#!/usr/bin/perl

$num1 = 10;
$num2 = 5;
$result = compare($num1,$num2);

print $result; <b># "is greater"</b>

sub compare {
    return "is greater" if $_[0] > $_[1];
    return "is smaller" if $_[0] < $_[1];
    return "is equal"  if $_[0] == $_[1];
}
</pre>
<p>Here is another way to see the same results:</p>
<pre name="code" class="php">
#!/usr/bin/perl

use strict;

$num1 = 10;
$num2 = 5;
$result = compare($num1,$num2);

print $result; # "is greater"

sub compare(@) {
	if ($_[0] > $_[1]) {
		"is greater"; # "return" operator not required
	}
	elsif($_[0] == $_[1]) {
		"is equal";
	}
	else {
		"is less than";
	}
}
</pre>
<p>As you can see, we didn't use the <tt>return</tt> operator in the example above. It is not required here because Perl will automatically return the value of the last statement evaluated. It's not a best practice to do it this way though. We strongly recommend that you keep your <tt>return</tt>s where they're supposed to be.</p>
<h3>Prototypes</h3>
<p>In order to bypass the flattening out of all the array and hash parameters into a single array, Perl allows us to specify prototypes for our subroutines. This tells our program if we're expecting an Array, or a Hash, or to treat the elements passed as individual references instead of flattening them out. It also lets us define which parameters are mandatory and which are optional.</p>
<p>There are ways of overriding (turning off) prototypes. By calling the subroutine in the "old" fashion (&amp;my_proto; or &amp;my_proto()) for instance, the checking will not be done. Calling subroutines as methods in Object Oriented Perl also turns it off.</p>
<p>The catch with prototypes is that you have to declare the subroutine BEFORE actually calling it. Look at the following example:</p>
<pre class="php" name="code">
#!/usr/bin/perl -w

@array = qw(a b c );

my_proto(@array,'test');

sub my_proto(@) {
	print "@_n";
}
<b># Warns the following message:  main::my_proto() called too early to check prototype at ./test.pl line 5.
# and prints "a b c test"</b>
</pre>
<p>In this example, the subroutine and its prototype are declared after the call. Perl warns that the call was too early to check prototype and treats the subroutine as if it didn't have any.  The correct way of doing it would be this:</p>
<pre class="php" name="code">
#!/usr/bin/perl -w

sub my_proto(@); <b># pre-declare the sub</b>

@array = qw(a b c );
my_proto(@array,'test');

sub my_proto(@) {
	print "@_n";
}
<b># Compilation error:
# Too many arguments for main::my_proto at ./test.pl line 8, near "'test')"
# Execution of ./test.pl aborted due to compilation errors.</b>
</pre>
<p>This time the script didn't even compile (remember that Perl is an interpreted AND compiled language). Prototype checking was in place and raised the error which aborted compilation.</p>
<p>You probably realized that the error message we got is the same as the ones we get when we fail to provide built-in functions the right parameters. That's exactly what prototyping does - it allows you to make your subroutines behave like built-in functions.</p>
<p>The <a href="http://perldoc.perl.org/perlsub.html#Prototypes" target="_blank">perlsub section in perldoc</a> shows the kinds of prototypes that we can use to mimick the built-in functions:</p>
<pre>
		Declared as		Called as

		sub mylink ($$)		mylink $old, $new
		sub myvec ($$$)		myvec $var, $offset, 1
		sub myindex ($$;$)	myindex &amp;getstring, "substr"
		sub mysyswrite ($$$;$)	mysyswrite $buf, 0, length($buf) - $off, $off
		sub myreverse (@)	myreverse $a, $b, $c
		sub myjoin ($@)		myjoin ":", $a, $b, $c
		sub mypop (@)		mypop @array
		sub mysplice (@$$@)	mysplice @array, @array, 0, @pushme
		sub mykeys (%)		mykeys %{$hashref}
		sub myopen (*;$)	myopen HANDLE, $name
		sub mypipe (**)		mypipe READHANDLE, WRITEHANDLE
		sub mygrep (&amp;@)		mygrep { /foo/ } $a, $b, $c
		sub myrand (;$)		myrand 42
		sub mytime ()		mytime
</pre>
<p><strong>Notes:</strong></p>
<ul>
<li>';' is used to separate mandatory (to the left of ; ) from optional fields (to the right).</li>
<li>@, $, %, etc. makes the sub require that exact element in the position in which it was declared.</li>
<li>sub mysub([@$%]) allows you to call mysub with a $var, or @array, or %hash, etc.</li>
<li>sub mysub($) when called with mysub(@array) will <strong>force the array to be handled in SCALAR context</strong></li>
</ul>
<p>Another catch of declaring subs with prototypes is that you will get a warning if you declare your sub with a given prototype first, and then again with the rest of the code and a different prototype. Let's look at a couple of examples to get a better idea of what I mean.</p>
<p><strong>Example 1</strong></p>
<pre class="php" name="code">
#!/usr/bin/perl -w

sub mysub(@); <b># defined in array context</b>

@array = qw(a b c);

mysub(@array);

sub mysub($) {  <b># defined in scalar context</b>
	print "@_n";
}
<b># Prototype mismatch: sub main::mysub (@) vs ($) at ./test.pl line 15.
# prints out "a b c"</b>
</pre>
<p><strong>Example 2</strong></p>
<pre class="php" name="code">
#!/usr/bin/perl -w

sub mysub($) {  <b># defined in scalar context</b>
	print "@_n";
}

@array = qw(a b c);

mysub(@array);

<b># works just fine
# prints out "3" due to the scalar context in which the sub is defined.</b>
</pre>
<h3>Lexical Scopes</h3>
<p>Perl by default is a very loose language. It lets you get away with things that other languages would never dream of - like using global variables indiscriminately. It's all fine and good if you want to write a quick and dirty script that isn't more than a few lines long, but if you're trying to build a complex application such as a bulletin board system (Matt Wright's wwwboard was written in (horrible) perl), you will probably find yourself missing a few toes after all the shots you foot took.</p>
<p>A solution for this problem is to ALWAYS use strict. Strict is a pragmatic module (or just pragma) that enforces several security measures such as having to pre-declare your variables, and another large list of constraints. It should always be the second line of your program (being the shebang the first line).</p>
<p>One of the things that use strict; enforces the most is to have you make good usage of lexical scopes. Lexical scopes mean that you can't access a variable that was not pre-declared, or somehow imported into the current block of code.</p>
<pre class="php" name="code">
#!/usr/bin/perl -w

$name = 'vinny';

myprint();

sub myprint() {
	print "$namen";
}
<b># main::myprint() called too early to check prototype at ./test.pl line 7.
# vinny</b>
</pre>
<p>The example above accesses the value of the global variable $name from within the subroutine. That is not a very safe thing to do. If we turn on strict, we get an error when trying to do that. The error, however, is because we didn't declare $name with either my, local, or our.</p>
<pre class="php" name="code">
#!/usr/bin/perl -w

use strict;

$name = 'vinny';

myprint();

sub myprint() {
	print "$namen";
}

<b># main::myprint() called too early to check prototype at ./test.pl line 7.
# Global symbol "$name" requires explicit package name at ./test.pl line 5.
# Global symbol "$name" requires explicit package name at ./test.pl line 11.
# Execution of ./test.pl aborted due to compilation errors.</b>
</pre>
<p>Changing the script above to comply with strict, we are once again able to access the global $name, but we still don't want to do that, especially if we want to modify the value of $name only inside the subroutine.</p>
<pre class="php" name="code">
#!/usr/bin/perl -w

use strict;

my $name = 'vinny'; <b># added my to comply with strict</b>

myprint();

print "$namen";

sub myprint() {
	$name .= " Alves"; <b># changes the original variable instead of a private one</b>
	print "$namen";
}

<b># main::myprint() called too early to check prototype at ./test.pl line 7.
# vinny Alves
# vinny Alves</b>
</pre>
<p>So it's best if we play it safe and not work on global variables at all. This is especially the case if you one day plan on writing scripts to use with Apache/mod_perl.</p>
<pre class="php" name="code">
#!/usr/bin/perl -w

use strict;

my $name = 'vinny'; <b># added <tt>my</tt> to comply with strict</b>

myprint($name); <b># calls the sub</b>

print "$namen"; <b># $name here still has the original value</b>

sub myprint() {
	my $name = shift;
	$name .= " Alves";
	print "$namen";
}
<b># main::myprint() called too early to check prototype at ./test.pl line 7.
# vinny Alves
# vinny</b>
</pre>
<h3>Context and wantarray</h3>
<p>Something that often catches Perl beginners off guard is the concept of context. Calling an @array in scalar context will return the number of elements, and not the elements themselves. We can mimick this behavior with wantarray. This is how it works:</p>
<pre class="php" name="code">
#!/usr/bin/perl

use strict;

my @array1 = qw(a b c d e);
my @array2 = reverse_or_count(@array1);
my $count = reverse_or_count(@array1);

print "@array2n";
print "$count";

sub reverse_or_count(@){
	my @arr = @_;
	if (wantarray) {
		return reverse @arr;
	}
	else {
		return $#arr + 1; <b># last index of @arr plus 1</b>
	}
}
</pre>
<p>Thanks to the wantarray operator returns true if the subroutine is being called in an array context, and false if not. With that kind of control, the sky is the limit <img src='http://usestrict.net/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> .</p>
<h3>Closures</h3>
<p>Closures are usually thought of as very advanced topics, but they're not that bad at all. They're basically a way to work with lexical variables inside referenced subroutines. OK, I admit that that sounded terrible, but with a simple example we can clarify it.</p>
<pre class="php" name="code">
#!/usr/bin/perl

use strict;

sub make_counter() {
	my $start = shift;
	return sub { $start++ }
}

my $from_ten = make_counter(10);
my $from_three = make_counter(3);

print $from_ten-&gt;();    <b># 10</b>
print $from_ten-&gt;();    <b># 11</b>
print $from_three-&gt;();  <b># 3</b>
print $from_ten-&gt;();    <b># 12</b>
print $from_three-&gt;();  <b># 4</b>
</pre>
<p>This is how it works: Our sub make_counter takes the initial parameter into its own private $start variable and then returns an anonymous subroutine - the auto-incrementation of $start.  So when we call make_counter(10) we are actually creating a reference to the auto-increment with the initial value of 10. The beauty of it is that the value isn't lost when it comes out of scope. It's saved in memory for the next time it's called. That's why calling $from_ten-&gt;() will increment on top the latest result.</p>
<p>What is even nicer is that we can create as many instances of that subroutine reference as we want. Calling $from_three-&gt;() will not impact the results of $from_ten-&gt;().</p>
<p>That is pretty much all there is to it. Use your creativity to do the rest.</p>
<p style="text-align:right;">« Basic I/O | <a href="http://usestrict.net/2008/10/05/perl-crash-course/" target="_self">TOC</a> | File and directory tests and manipulation »</p>
]]></content:encoded>
			<wfw:commentRss>http://usestrict.net/2009/03/perl-crash-course-subroutines/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

