<?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 Course Howto</title>
	<atom:link href="http://usestrict.net/tag/perl-course-howto/feed/" rel="self" type="application/rss+xml" />
	<link>http://usestrict.net</link>
	<description>Professional IT Solutions &#38; Training</description>
	<lastBuildDate>Fri, 10 Feb 2012 12:01:05 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</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>
<p>[ad#middle_end]</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>
<p>[ad#middle_end]</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>8</slash:comments>
		</item>
		<item>
		<title>Perl Crash Course: Control Structures</title>
		<link>http://usestrict.net/2009/04/perl-crash-course-control-structures/</link>
		<comments>http://usestrict.net/2009/04/perl-crash-course-control-structures/#comments</comments>
		<pubDate>Wed, 15 Apr 2009 03:06:22 +0000</pubDate>
		<dc:creator>vinny</dc:creator>
				<category><![CDATA[Perl]]></category>
		<category><![CDATA[Control Structures]]></category>
		<category><![CDATA[Perl Course Howto]]></category>

		<guid isPermaLink="false">http://usestrict.net/?p=409</guid>
		<description><![CDATA[Basics on Perl control structures]]></description>
			<content:encoded><![CDATA[<p><strong>by André Batosti<br />
revision: Fernando Giorgetti and Vinny Alves</strong></p>
<p>Control Structures are used to control the flow of a program. We are going to see programs that can iterate (loop) or make decisions (conditionals) based on the state of variables.</p>
<p>More interesting possibilities arise when we introduce control structures and looping. Perl supports lots of different kinds of control structures which tend to be like those in C, but are very similar to Pascal, too.<br />
<span id="more-409"></span><br />
<code><br />
</code></p>
<h3>Conditionals</h3>
<p>The simplest control structures are the <tt>if</tt> and <tt>unless</tt> statements. Its syntax basically follows the rule below:</p>
<pre name="code" class="php">
if ( expression ) {
    instruction1;
    instruction2;
}
</pre>
<p>Value obtained from &#8220;expression&#8221;, determines whether it will be considered as <tt>true</tt> or <tt>false</tt>. Table below helps you to identify the meaning of values based on how Perl interprets expressions.</p>
<table border="1" cellpadding="0">
<tbody>
<tr>
<td><strong>Expression</strong></td>
<td><strong>String/Number?</strong></td>
<td><strong>Boolean value</strong></td>
</tr>
<tr>
<td>0</td>
<td>number</td>
<td>false</td>
</tr>
<tr>
<td>0.0</td>
<td>number</td>
<td>false</td>
</tr>
<tr>
<td>0.0000</td>
<td>number</td>
<td>false</td>
</tr>
<tr>
<td>&#8220;&#8221; or &#8221;</td>
<td>string</td>
<td>false</td>
</tr>
<tr>
<td>&#8220;0&#8243;</td>
<td>string</td>
<td>false</td>
</tr>
<tr>
<td>&#8220;0.0&#8243;</td>
<td>string</td>
<td><strong>true</strong></td>
</tr>
<tr>
<td>undef</td>
<td>N/A</td>
<td>false</td>
</tr>
<tr>
<td>42 &#8211; (6 * 7)</td>
<td>number</td>
<td>false</td>
</tr>
<tr>
<td>&#8220;0.0&#8243; + 0.0</td>
<td>number</td>
<td><strong>false</strong></td>
</tr>
<tr>
<td>&#8220;0E0&#8243;</td>
<td>number</td>
<td><strong>true</strong></td>
</tr>
<tr>
<td>0E0</td>
<td>number</td>
<td><strong>false</strong></td>
</tr>
<tr>
<td>&#8220;foo&#8221;</td>
<td>string</td>
<td>true</td>
</tr>
</tbody>
</table>
<p>Everything in Perl is true, except:</p>
<ul type="disc">
<li>the strings &#8220;&#8221; (the empty string) and &#8220;0&#8243; (the string containing only the character, 0), or any string expression that evaluates to either &#8220;&#8221; (the empty string) or &#8220;0&#8243;.</li>
<li>any numeric expression that evaluates to a numeric 0.</li>
<li>any value that is not defined (i.e., equivalent to undef).</li>
</ul>
<p>A very simple example of a real &#8220;if statement&#8221; would be:</p>
<pre name="code" class="php">
if ( $name ) {
    print "Non empty string";
}
else {
    print "Empty string";
}
</pre>
<p>Another example, to illustrate the syntax of the &#8220;if&#8221; statement:</p>
<pre name="code" class="php">
if ( $money &lt;= 0 ) {
    print "You are out of money";
}
elsif ( $money &gt; 1000000 ) {
    print "You are a millionaire";
}
else {
    print "You are probably better than I am";
}
</pre>
<p>Blocks of code in Perl are enclosed by curly braces {   }. They are <strong>always required</strong> inside a control structure (except for cases where we use idiomatic ifs &#8211; see more below).</p>
<p>Two things to mention:</p>
<p>1 &#8211; <tt>elsif</tt> spelling;<br />
2 &#8211; both <tt>elsif</tt> and <tt>else</tt> statements are optional.</p>
<p>Another conditional statement we need to mention is the <tt>unless</tt>. Its meaning is the opposite of an <tt>if</tt> statement. It will only execute a block of code if expression is NOT true.</p>
<p>Let&#8217;s look at an example:</p>
<pre name="code" class="php">
if  ( $num == 10 ) { #Usual if statement
    print "Number is equal to 10";
} else {
    print "Number not equal to 10";
}

# Unless statement that will execute the block of code below
# if number's value is not 10 (same thing as the else statement above)

unless ( $num == 10 ) {
    print "Number not equal to 10";
}
else {
    print "Number is equal to 10";
}
</pre>
<h3>Action based on statement test</h3>
<p>You can test a single statement and perform a pre-defined action in case it is true or another one if statement is false.</p>
<p>For example:</p>
<pre name="code" class="php">
    print "You are a man" if ($gender eq "M"); # parentheses are optional here, since only one expression is evaluated
</pre>
<p><code><br />
</code><br />
[ad#middle_end]<br />
<code><br />
</code></p>
<h3>Ternary or Trinary Operator</h3>
<p>Like many other programming languages, Perl offers the ternary (aka trinary) operator &#8220;?:&#8221; which behaves just like if/elsif/else: </p>
<pre name="code" class="php">
print "You are a " . (($gender eq "M") ? "man" : "woman") . "n";
# read: if $gender eq "M" then "man" else "woman"

# or perhaps
($birthday == $today) ? print "Happy birthday!" : print "Have a good day";
</pre>
<p>Mimmic elsif this way:</p>
<pre name="code" class="php">
$month = (localtime)[4]; # fifth element of localtime in list context returns month, base 0;

print "The month is now " .
($month == 0) ? "January" :
($month == 1) ? "February" :
($month == 3) ? "March" :
                      "something other than Jan, Feb, or March";
</pre>
<h3>Operators</h3>
<p>Initially we will introduce the testing operators. They rely on a test being considered as true or false. Following you can see a few examples:</p>
<pre name="code" class="php">
$a == $b                      # Is $a numerically equal to $b?
# Beware: Don't use the = operator.
$a != $b                       # Is $a numerically unequal to $b?
$a eq $b                       # Is $a string-equal to $b?
$a ne $b                       # Is $a string-unequal to $b?
</pre>
<p>Perl also supports the logical operators &#8220;OR&#8221; and &#8220;AND&#8221;. The &#8220;OR&#8221; operator is represented by the &#8220;||&#8221; characters while the &#8220;AND&#8221; is represented by &#8220;&amp;&amp;&#8221; characters.</p>
<p>Lets go through a few examples:</p>
<pre name="code" class="php">
# If value of number is greater than 10 or lesser than 5
if ( ( $num &gt; 10 ) || ( $num &lt; 5 ) ) {
    ...
}

# If language is equal to "perl" and num is 10, or, if num is 0 (or has a "false" value)
if ( (( $language eq "perl" ) &amp;&amp; ( $num == 10 )) || !( $num ) ) {
    ...
}
</pre>
<h3>Loops</h3>
<p>We have several statements to perform iterations using Perl. Perl supports: <tt>while</tt>, <tt>until</tt>, <tt>do ... while</tt>, <tt>for</tt> and <tt>foreach</tt> statements.</p>
<h3><em>While</em></h3>
<p>Performs the iteration while the given expression is true. Syntax:</p>
<pre name="code" class="php">
while (expression) {
    instruction1;
    instruction2;
    ...
}
</pre>
<h3><em>Until</em></h3>
<p>It is the opposite of <tt>while</tt>. So take it as, in example:</p>
<pre name="code" class="php">
while (!(expression)) {
    instruction1;
    instruction2;
}

#same as
until (expression) {
   instruction1;
   instruction2;
}
</pre>
<h3><em>Do .. While</em></h3>
<p>Its functionality is almost the same as for the normal &#8220;while&#8221; statement, but with this kind of control structure you guarantee that the block of code will be executed at least once.</p>
<pre name="code" class="php">
do {
    instruction1;
    instruction2;
} while (expression);
</pre>
<h3><em>For</em></h3>
<p>It&#8217;s a C like style. Syntax:</p>
<pre name="code" class="php">
for (initialize; expression; increment/decrement) {
    instruction1;
    instruction2;
    ...
}
</pre>
<ul type="disc">
<li>The <em>initialize</em> statement is basically used to initialize the variable that will be used on the test statement. It can also be used anywhere in the block. Declare it with <tt>my</tt> to keep it private to the for block;</li>
<li><em>Expression</em> follows the same rule for <tt>if</tt> or <tt>while</tt>. It will be tested, and if its return is true, block code will be executed;<em></em></li>
<li><em>Increment/decrement </em>is then executed<em></em></li>
</ul>
<p>Real example:</p>
<pre name="code" class="php">
for ($i = 0; $i &lt; 10; $i++ ) {
    printf "Iteration number: %sn", $i;
}
</pre>
<p>Another good example (not using a numeric expression):</p>
<pre name="code" class="php">
for ( @names = ('John', 'Paul', 'Roger', 'David'); @names; shift(@names) ) {
    print "$names[0]n";
}

# Or work on 2 expressions at the same time
for ($i = 0, $j = 10; $i&lt;=10,$j&gt;=0; $i++, $j--) {
    print "$i    $jn";
}

# Or kick off an infinite loop
for ( ; ; ) {
    instruction1;
    instruction2;
}
</pre>
<h3><em>Foreach</em></h3>
<p>It is another control structure that allows iteration, but here you can iterate over an array.</p>
<p>Following you can see a few examples of it:</p>
<pre name="code" class="php">
@names = ('John', 'Paul', 'Roger', 'David');

#Passing through all names
foreach $name (@names) {
    printf "%sn", $name;
}
</pre>
<p>The scalar variable is optional to the <tt>foreach</tt> statement. So you can bypass it by doing:</p>
<pre name="code" class="php">
@names = ('John', 'Paul', 'Roger', 'David');

#Passing through all names
foreach (@names) {
    printf "%sn", $_;
}
</pre>
<p>If you don&#8217;t specify a scalar variable to get each iteration, then the default scalar ($_) will be used. Note that <tt>for</tt> can also be used as a synonym to <tt>foreach</tt> &#8211; same exact functionality, but without the <em>each</em> portion of the word.</p>
<h3><em>Loop flow control</em></h3>
<p>We have a few special commands to help us controlling the flow under a loop statement. Here we go.</p>
<p><tt>last</tt></p>
<p>It is similar to the &#8220;break&#8221; statement used on C programming language (as well as in several others). Tells Perl to skip the current loop statement, or even, to skip a labeled loop statement. Take a look at the example below:</p>
<pre name="code" class="php">
@names = ('fernando', 'smith', 'Mark', 'John');
foreach (@names) {
    last if $_ eq "John";
    print "Name is " . $_ . "n";
}
</pre>
<p><tt>next</tt></p>
<p><tt>next</tt> has the same function as the &#8220;continue&#8221; loop statement used in C. Used to force your loop statement to go to the next iteration. In example:</p>
<pre name="code" class="php">
@names = ('fernando', 'smith', 'Mark', 'John');
foreach (@names) {
    next if $_ eq "smith";
    print "Name is " . $_ . "n";
}
</pre>
<p>The example above will just force the &#8220;foreach&#8221; statement to read next iteration once &#8220;smith&#8221; is the value read from the &#8220;names&#8221; array.</p>
<p>If you need to work on multiple levels of loops, you can tell <tt>next</tt> and <tt>last</tt> which named block to work on:</p>
<pre name="code" class="php">
LINE: while (<STDIN>) {
	next LINE if /^#/;	# discard comments
	...
}
</pre>
<p>[ad#middle_end]</p>
<p style="text-align:right;"><a href="http://usestrict.net/2009/04/07/perl-crash-course-basic-regular-expressions/">« Basic Regular Expressions</a> | <a href="http://usestrict.net/2008/10/05/perl-crash-course/" target="_self">TOC</a> | Basic I/O »</p>
]]></content:encoded>
			<wfw:commentRss>http://usestrict.net/2009/04/perl-crash-course-control-structures/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>
<p>[ad#middle_end]</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>[ad#middle_end]</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>
		<item>
		<title>Perl Crash Course: Gettin&#8217; jiggy wit it</title>
		<link>http://usestrict.net/2009/02/perl-crash-course-gettin-jiggy-wit-it/</link>
		<comments>http://usestrict.net/2009/02/perl-crash-course-gettin-jiggy-wit-it/#comments</comments>
		<pubDate>Sun, 01 Feb 2009 18:27:26 +0000</pubDate>
		<dc:creator>vinny</dc:creator>
				<category><![CDATA[newbies]]></category>
		<category><![CDATA[Perl]]></category>
		<category><![CDATA[Perl Course Howto]]></category>

		<guid isPermaLink="false">http://usestrict.net/?p=43</guid>
		<description><![CDATA[Built in Perl functions for Scalars, Arrays, and Hashes]]></description>
			<content:encoded><![CDATA[<p>So far we&#8217;ve seen how Perl&#8217;s basic data structures work and also how to put them all together. Now it&#8217;s time to see what built-in functions and techniques Perl provides us to work with scalars, arrays, and hashes.</p>
<p><strong>General functions</strong></p>
<p><em><strong>print [FILE HANDLE] list of data</strong></em></p>
<p>Used to print data. If not passed a FILE HANDLE, it will print directly to STDOUT. Interpolation rules apply. Some interesting details about <em>print</em> are:</p>
<pre class="brush:perl">

print @array;  # prints all elements of @array with
               # no spaces between them
print "@array";  # prints the elements WITH spaces between them
print $var1, $var2, @array;  # prints values with no spaces between them
print FH "some data";  # prints the string "some data" inside file represented by FH (see <em>open </em>below).
# Note the lack of comma between the FH and the data to be printed.
</pre>
<p><em><strong>open (FILE HANDLE, mode, filename)</strong></em> or  <em><strong>open (FILE HANDLE, &#8220;modefilename&#8221;)</strong></em></p>
<p>Opens a file or pipe for reading/writing/appending. Normally filehandles tend to be constants in uppercase, but it&#8217;s good practice to use variables to hold your filehandles. That way you can pass them between functions without occupying the main namespace. There are 2 styles of <tt>open</tt> &#8211; old style with 2 parameters and new style with 3.</p>
<p><span id="more-43"></span></p>
<p><em>open</em>&#8216;s modes are:<br />
&lt; (readonly),<br />
&gt; (create/write/truncate),<br />
&gt;&gt; (create/write/append),<br />
+&lt; (read/write/truncate),<br />
+&gt; (create/read/write/truncate),<br />
+&gt;&gt; (create/read/write/append)</p>
<pre class="brush:perl">

# old style - for reading
open (FH, "&lt;/path/to/somefile.txt") || die("Can't open file: $!n"); # $! returns the system error
# do something here
close(FH);

# new style - also for reading
open (my $fh, "&lt;", "/path/to/somefile.txt") || die("Can't open file: $!n");
# do something here
close($fh);</pre>
<p>When working with pipes, filenames begining with | indicate a pipe to write to. Filenames ending with | indicate filenames to read from. Use the special minus &#8216;-&#8217; sign to read from standard input.</p>
<p> <em><strong>printf($format_string,$value1[,$value2,$valueN])</strong></em> <tt>print</tt>&#8216;s older brother &#8211; takes patterns and prints a formatted string. It is extremely powerful and most people do not use it to its full extent.</p>
<p>  These are the formatting options you can use:</p>
<table style="border: 1px #000000 solid" border="0">
<tbody>
<tr>
<th style="border: 1px #000000 solid" align="left">Format</th>
<th style="border: 1px #000000 solid" align="left">Result</th>
</tr>
<tr>
<td style="border: 1px #000000 solid">%%</td>
<td style="border: 1px #000000 solid">A literal percent sign</td>
</tr>
<tr>
<td style="border: 1px #000000 solid">%c</td>
<td style="border: 1px #000000 solid">A character with the given ASCII code</td>
</tr>
<tr style="border: 1px #000000 solid">
<td style="border: 1px #000000 solid">%s</td>
<td style="border: 1px #000000 solid">A string</td>
</tr>
<tr>
<td style="border: 1px #000000 solid">%d</td>
<td style="border: 1px #000000 solid">A signed integer (decimal)</td>
</tr>
<tr>
<td style="border: 1px #000000 solid">%u</td>
<td style="border: 1px #000000 solid">An unsigned integer (decimal)</td>
</tr>
<tr>
<td style="border: 1px #000000 solid">%o</td>
<td style="border: 1px #000000 solid">An unsigned integer (octal)</td>
</tr>
<tr>
<td style="border: 1px #000000 solid">%x</td>
<td style="border: 1px #000000 solid">An unsigned integer (hexadecimal)</td>
</tr>
<tr>
<td style="border: 1px #000000 solid">%X</td>
<td style="border: 1px #000000 solid">An unsigned integer (hexadecimal using uppercase characters)</td>
</tr>
<tr>
<td style="border: 1px #000000 solid">%e</td>
<td style="border: 1px #000000 solid">A floating point number (scientific notation)</td>
</tr>
<tr>
<td style="border: 1px #000000 solid">%E</td>
<td style="border: 1px #000000 solid">A floating point number, uses E instead of e</td>
</tr>
<tr>
<td style="border: 1px #000000 solid">%f</td>
<td style="border: 1px #000000 solid">A floating point number (fixed decimal notation)</td>
</tr>
<tr>
<td style="border: 1px #000000 solid">%g</td>
<td style="border: 1px #000000 solid">A floating point number (%e or %f notation according to value size)</td>
</tr>
<tr>
<td style="border: 1px #000000 solid">%G</td>
<td style="border: 1px #000000 solid">A floating point number (as %g, but using .E. in place of .e. when<br />
appropriate)</td>
</tr>
<tr>
<td style="border: 1px #000000 solid">%p</td>
<td style="border: 1px #000000 solid">A pointer (prints the memory address of the value in hexadecimal)</td>
</tr>
<tr>
<td style="border: 1px #000000 solid">%n</td>
<td style="border: 1px #000000 solid">Stores the number of characters output so far into the next variable in<br />
the parameter list</td>
</tr>
</tbody>
</table>
<p></p>
<pre class="brush:perl">

printf("Hello, My name is %s. Today is the %dth day of %s.", $name,$day,$month);
printf("This item costs $%.2f.",$some_number);  # escape the dollar sign
printf("I need 2 %%'s to get one printed with printf");
</pre>
<p><em><strong>sprintf</strong></em><em><strong>($format_string,$value1[,$value2,$valueN])</strong></em></p>
<p>Works the same as printf, but instead of printing the output, it returns the formatted string (allowing you to store it in a variable for later use).</p>
<pre class="brush:perl">

$string1 = sprintf("Hello, My name is %s. Today is the %dth day of %s.", $name,$day,$month);
$string2 = sprintf("This item costs $%.2f.",$some_number);  # escape the dollar sign
$string3 = sprintf("I need 2 %%'s to get one printed with printf");
</pre>
<p>[ad#middle_end]</p>
<p><em><strong>warn($message)</strong></em></p>
<p>Use <tt>warn</tt> to print messages into STRERR without exiting your script. Besides the regular usage of letting the user know when something goes bad (but not fatally so), I also find it handy to filter data from a given input file using <tt>print</tt> and <tt>warn</tt> along with shell redirectors (&gt;log.out and 2&gt;err.out). See the example below to better understand what I&#8217;m talking about.</p>
<pre class="brush:perl">

# in odd_even.pl
foreach my $i (0..10) { # .. = "to", so for $i == 0 to $i == 10
	if ($i % 2 == 0) { # Modulus (%)  operator, returns the remainder of a division
		print "$in"; # output to STDOUT
	}
	else {
		warn "$in"; # output to STDERR
	}
}

# in the command line
./odd_even.pl &gt; even.txt 2 &gt; odd.txt
</pre>
<p><em><strong>die($message)</strong></em></p>
<p>Print a message into STDERR and exit the script. If the message inside the <tt>die</tt> statement ends in a newline, only the message will be printed. If no newline is found, it will print additional information such as line number and script name.</p>
<pre class="brush:perl">

if ($some_fatal_error) {
	die("ACK!! Something went really badn"); # prints out "ACK!! Something went really bad"
}

if ($some_other_error){
	die("ACK!! Something went really bad"); # prints out "ACK!! Something went really bad at script.pl line someline"
}
</pre>
<p><strong>Scalar functions</strong></p>
<p><em><strong>split (/pattern/, $string [,number_of_elements])</strong></em><br />
<tt>split</tt> breaks a string at a given pattern into an arbitrary number of pieces. It returns a list which is usually assigned into an array for later use. Use an unescaped &#8216;|&#8217; (pipe) to split strings at each letter.</p>
<pre class="brush:perl">

$string = "Hello World";
@array = split /|/,$string; # same as @array = ('H','e','l','l','o',' ','W','o','r','l','d');

$string2 = "Name,Age,Street,Phone_number,Skills";
($name,$age,$rest) = split (/,/,$string2,3); # $name has 'Name', $age has 'Age', and $rest has 'Street,Phone_number,Skills'
</pre>
<p><em><strong>substr($string,offset[,length])</strong></em><br />
Returns a piece of a string starting from a given offset and having a given length. If the length is ommitted, it will return until the end of the string. Positive offsets count from left to right. Negative offsets count from right to left. It is also handy to get padding done on a string</p>
<pre class="brush:perl">

$string = "Hello World";
print substr($string,0); # Hello World
print substr($string,3,4); # lo W
print substr($string,-5); # World
print substr($string,-5,2); # Wo

$padding_template = "00000";

foreach my $i (10, 100, 1000, 10000) {

	print substr($padding_template . $i , (length($padding_template) * -1)), "n";
	# the line above will evaluate to the following stirng:
	# print substr(00000$i,-5),n; where $i will be 10, then 100, then 1000, then 10000

}

# results in
# 00010
# 00100
# 01000
# 10000
</pre>
<p><strong><em>chop($string)<br />
</em></strong>Used to cut off and return the last character of a string<strong><em>.</em></strong> The variable is altered automatically. <em>Note:</em> you cannot <em>chop</em> on a literal string. The value to be <em>chop</em>ped must reside in a variable. The reason for that is due to <tt>chop</tt> modifying the original string to hold the <tt>chop</tt>ped version. </p>
<pre class="brush:perl">

$string = "Hello World";
$chopped = chop($string);

print $string; # Hello Worl
print $chopped; # d
</pre>
<p><strong><em>chomp($string)</em></strong><br />
Similar to <em>chop</em>, however it will only remove the last character if and only if it is a newline (n). The same applies to not being able to <em>chomp</em> a literal string. See the shorthand example if you want to assign/<em>chomp</em> during the same command.</p>
<pre class="brush:perl">

$string = "Hello World";
chomp($string); # no change, since there's no n at the end of $string

chomp($string2 = "with newline n"); # shorthand version
print $string2, $string; # with newlineHello World
</pre>
<p><strong><em>pack</em></strong> and <strong><em>unpack</em></strong><br />
A couple of the most powerful string manipulation functions (inherited from C), it&#8217;s so complex that I recommend that you read <a href="http://perldoc.perl.org/functions/pack.html">this</a> to see how it works.</p>
<p><strong>Array functions</strong></p>
<p><strong><em>join</em></strong><br />
Opposite of <tt>split</tt>. Takes an array and <tt>join</tt>s its values into a string using nothing, a given character, or a string as field separator. I find it handy to create large SQL queries with it. (See example below).</p>
<pre class="brush:perl">

@array = qw(Red Green Blue Black); # qw() puts double quotes around each word separated by space
$string = join(',',@array); # $string is "Red,Green,Blue,Black"
</pre>
<p><strong><em>shift</em></strong> and <strong><em>unshift</em></strong><br />
Use shift to remove and assign the first element of an array, and unshift to do the opposite. Shift is mostly used inside subroutines to get elements from the special @_ array (@_ contains all parameters passed onto a subroutine).</p>
<pre class="brush:perl">
@colors = qw(Red Green Blue Black);

$color = shift @colors; # or shift(@colors);
print "@colors";  # Green Blue Black;
print $color; # Red

unshift(@colors,$color);
print "@colors"; # Red Green Blue Black
</pre>
<p><strong><em>pop</em></strong> and <strong><em>push</em></strong><br />
Similarly to <tt>shift</tt> and <tt>unshift</tt>, <tt>pop</tt> and <tt>push</tt> work on the right site of an array.</p>
<pre class="brush:perl">

@pets = qw(Cat Dog Bird Fish);
$mypet = pop @pets;
print $mypet; # Fish
print "@pets"; # Cat Dog Bird

push(@pets,$mypet);
print "@pets"; # Cat Dog Bird Fish
</pre>
<p><strong><em>array slices</em></strong><br />
Not a function, but a syntax structure which allows you to access subsets of an array. Keep in mind Perl&#8217;s singular/plural constructs (using @ instead of $) while using a list, array, or range as your index.</p>
<pre class="brush:perl">

@pets = qw(Cat Dog Bird Fish);
print $pets[0]; # Cat - NOT a slice
print @pets[0,1,2]; # CatDogBird
print @pets[0..2]; # same thing
print @pets[qw(0 1 2)]; # same thing
</pre>
<p><strong>Hash functions</strong></p>
<p><strong><em>each</em></strong><br />
<tt>each</tt> iterates through the key/value pairs of a hash, returning them in a list context.</p>
<pre class="brush:perl">

while(($key,$value) = each (%hash)) {

	print $key, " =&gt; ", $value, "n"; 

}

# Prints
# key1 =&gt; val1
# key2 =&gt; val2
</pre>
<p><strong><em>exists</em></strong><br />
Checks for the existence of a key in a hash. Will return true even if the key&#8217;s value is false (undefined, empty string, zero, etc.).</p>
<pre class="brush:perl">

%hash = (key1 => undef,
         key2 => 'val2');

print "Got it!!" if exists($hash{key1}); # returns Got it!!
</pre>
<p><strong><em>delete</em></strong><br />
Removes a key/value pair from a hash. Use it when you want <tt>exists</tt> to return false.</p>
<pre class="brush:perl">
delete($hash{key1});

print "Got it!!" if exists $hash{key1}; # does not print anything
</pre>
<p>[ad#middle_end]</p>
<p style="text-align:right;"><a href="http://usestrict.net/2008/11/20/perl-crash-course-references-and-complex-data-structures-cds/" target="_self">« References and Complex Data Structures (CDS)</a> | <a href="http://usestrict.net/2008/10/05/perl-crash-course/" target="_self">TOC</a> | <a href="http://usestrict.net/2009/04/07/perl-crash-course-basic-regular-expressions/">Basic Regular Expressions »</a></p>
]]></content:encoded>
			<wfw:commentRss>http://usestrict.net/2009/02/perl-crash-course-gettin-jiggy-wit-it/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Perl Crash Course: References and Complex Data Structures (CDS)</title>
		<link>http://usestrict.net/2008/11/perl-crash-course-references-and-complex-data-structures-cds/</link>
		<comments>http://usestrict.net/2008/11/perl-crash-course-references-and-complex-data-structures-cds/#comments</comments>
		<pubDate>Thu, 20 Nov 2008 14:48:55 +0000</pubDate>
		<dc:creator>vinny</dc:creator>
				<category><![CDATA[Perl]]></category>
		<category><![CDATA[Perl Course Howto]]></category>

		<guid isPermaLink="false">http://usestrict.wordpress.com/?p=200</guid>
		<description><![CDATA[References and Complex Data Structures (CDS) Now that we have a pretty good understanding of the 3 types of data in Perl, it&#8217;s time we bump it up a notch and put them all together. Perl is most famous for its text manipulation using regular expressions, but it should also be noted by the ability [...]]]></description>
			<content:encoded><![CDATA[<p><span style="font-size:18px;">References and Complex Data Structures (CDS)</span></p>
<p>Now that we have a pretty good understanding of the 3 types of data in Perl, it&#8217;s time we bump it up a notch and put them all together. Perl is most famous for its text manipulation using regular expressions, but it should also be noted by the ability to create multilevel data structures, regardless of them being scalars, arrays, or hashes.</p>
<p><span id="more-21"></span></p>
<p>One way that I like to explain multilevel or multidimensional data is by taking &#8216;Folders&#8217; panel the Windows Explorer windows as example:</p>
<div id="attachment_202" class="wp-caption alignnone" style="width: 188px"><a href="http://usestrict.net/wp-content/uploads/2008/11/multilevel_folders1.gif"><img src="http://usestrict.net/wp-content/uploads/2008/11/multilevel_folders1.gif" alt="Example of Multilevel Folders" title="Multilevel Folders" width="178" height="292" class="size-full wp-image-202" /></a><p class="wp-caption-text">Example of Multilevel Folders</p></div>
<p>As you can see (despite the bad image quality), there is the main drive (root variable), which contains several folders (arrays/hashes) or files (scalar elements). These folders in turn can contain other folders (arrays/hashes) and files (scalar elements). In Perl you can have any kind of variable (array, hash, or scalar) containing any number of nested arrays, hashes, or scalars. This is done thanks to <em>references</em>, and anonymous arrays and hashes.</p>
<p>Here&#8217;s how it works:</p>
<p>When you create a variable, its name and contents get stored in your computer&#8217;s memory. A reference is a (<em>singular</em>) pointer in memory to another memory address. The most common way of getting a reference to a data structure is to escape the identifier symbol ($, @, or %) with a backslash.</p>
<pre name="code" class="php">
$array_ref = @array;
$hash_ref = %hash;

print "$array_refn";  #WRONG: you will get something similar to ARRAY(0x125f6e0)
print "$hash_refn"; #WRONG: you will get something similar to HASH(0x125f6e0)

print $array_ref->[0]; #RIGHT: prints the first element of the referenced array
print ${$array_ref}[0]; #RIGHT: same results as above
print $$array_ref[0]; #RIGHT: same thing

print $hash_ref-&gt;{key1}; #RIGHT: prints value for key 'key1'
print ${$hash_ref}{key1}; #RIGHT: same as above
print $$hash_ref{key1}; #RIGHT: same thing
</pre>
<p>In the example above, we see that we can&#8217;t just print the value of a referenced data structure by calling print and the scalar that&#8217;s holding it (scalar because it&#8217;s holding <em>one</em> reference &#8211; no, I can&#8217;t stress that enough). We need to <em>dereference</em> our reference.</p>
<p>The two ways of dereferencing a reference (<a href="http://www.perlfoundation.org/perl5/index.cgi?tmtowtdi">TMTOWTDI</a>) are either by delimiting our ref within ${} or by using the -&gt;. You may also have noticed that we use <b>-&gt;[]</b> for arrays and <b>-&gt;{}</b> for hashes. Use <em>@{$var}</em> and <em>%{$var}</em> if you want to dereference the whole array or hash, instead of just one key or element. Same goes for <em>@$var</em> and <em>%$var</em>.</p>
<p>To create multilevel data, you can nest the references inside the assignment lists:</p>
<pre name="code" class="php">
@arr1 = (1,2,3); # Regular single level array

@multi = (@arr1,4,5); # WRONG: results in (1,2,3,4,5)
@multi = (@arr1,4,5); # RIGHT: 3 element array, being the first element another array

$multi-&gt;[0]; # prints ARRAY(0x1233ad8)
$multi-&gt;[1]; # prints 4

$multi-&gt;[0]-&gt;[0]; # prints 1 - the first element of @arr1
$$multi[0][0]; # same thing
${$multi}[0][0]; # ditto
</pre>
<p>It is also possible and even common to assign anonymous (unnamed) data structures to scalars directly. While lists are bound by parens or the qw() function (seen in detail further along), anonymous arrays are bound by square brackets ([ ]) and anonymous hashes by braces ({ }).</p>
<pre name="code" class="php">
$arr = []; # kick off $arr as a reference to an empty, unnamed array
$arr2 = [ 1,2,3,4 ] ; # does not have to start off empty

$arr-&gt;[0] = 'a'; # first element of $arr is now 'a'

$hsh = {}; # empty anonymous hash
$hsh->{somekey} = 'somevalue'; # added key 'somekey' with value 'somevalue'

$hsh2 =  {
                'key1' =&gt; 'val1',
                'key2' =&gt; 'val2',  # you can leave the comma
             } ; # even though you do not have any more pairs
</pre>
<p>Now that you have your references, put it all together.</p>
<pre name="code" class="php">
@multi = ($arr, $arr2, $hsh, $hsh2, 1, 'a'); # data structure galore

print $multi->[1]->[-1]; # last element of second element: 4
                                 # Lets put it all together, no temp scalars
$VAR1 = [
                  {
                       key2' => [
                                            0,
                                            1,
                                            2,
                                            3
                                        ],
                      'key1' => 'val1'
                   },
                   'a',
                   'something',
                   [
                      'red',
                      'blue',
                      'green'
                    ]
            ];

# Results:

print $VAR1->[0]->{key1}; # val1
print $VAR1->[0]->{key2}; # ARRAY(0x1233ad8) - needs dereferencing
print $VAR1->[0]->{key2}->[2]; # third element of key2: 2
print $VAR1->[-1]->[-2]; # blue
$VAR1->[-1]->[-2] = 'yellow'; # was blue, is now yellow
</pre>
<p>If you find this all mind boggling, don&#8217;t worry &#8211; you&#8217;re not alone. Fortunately we can rely on a very handy module called Data::Dumper which is really handy for times like these. More on it later on.</p>
<p style="text-align:right;"><a href="http://usestrict.net/2008/10/31/perl-crash-course-hashes/" target="_self">« Hashes</a> | <a href="http://usestrict.net/2008/10/05/perl-crash-course/" target="_self">TOC</a> | <a href="http://usestrict.net/2009/02/01/perl-crash-course-gettin-jiggy-wit-it/">Gettin&#8217; jiggy wit it »</a></p>
]]></content:encoded>
			<wfw:commentRss>http://usestrict.net/2008/11/perl-crash-course-references-and-complex-data-structures-cds/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Perl Crash Course: Hashes</title>
		<link>http://usestrict.net/2008/10/perl-crash-course-hashes/</link>
		<comments>http://usestrict.net/2008/10/perl-crash-course-hashes/#comments</comments>
		<pubDate>Fri, 31 Oct 2008 13:15:11 +0000</pubDate>
		<dc:creator>vinny</dc:creator>
				<category><![CDATA[Perl]]></category>
		<category><![CDATA[Perl Course Howto]]></category>

		<guid isPermaLink="false">http://usestrict.wordpress.com/?p=166</guid>
		<description><![CDATA[Hashes The hash is, in my honest opinion, the most important data structure in Perl. It is nothing more than what other languages call an Associative Array, but it is very powerful and one of the key features of Object Oriented Perl. If Associative Array still doesn&#8217;t ring a bell, then think of a file [...]]]></description>
			<content:encoded><![CDATA[<p><span style="font-size:18px;">Hashes</span></p>
<p>The hash is, in my honest opinion, the most important data structure in Perl. It is nothing more than what other languages call an Associative Array, but it is very powerful and one of the key features of Object Oriented Perl.</p>
<p><span id="more-19"></span></p>
<p>If Associative Array still doesn&#8217;t ring a bell, then think of a file cabinet. Your every day file cabinet holds files that are identified by tags. These tags are the keys to your files. The content of each file can be considered its value. So the same happens to a hash. It&#8217;s an array of key/value pairs. You can identify a hash by the symbol that starts its variable name:</p>
<pre name="code" class="php">
%some_hash
%a
%_a_very_big_hash_name
</pre>
<p>% was chosen to identify hashes because of the similarity to a key/value pair&#8230;</p>
<p>Hash keys are unique, and can be made up of any character and be of any size. Depending on your key name, you might need to use it between single or double quotes.</p>
<p>Hash values can be anything you would normally assign to a scalar variable, including anonymous arrays and anonymous hashes (more on this when we see <em>Complex Data Structures</em>).</p>
<p>Interpolation rules apply just like with any other quoting &#8211; either for keys or values. Use &#8220;=&gt;&#8221; (fancy comma) to separate keys from values. Regular commas work too, but are more difficult on the eyes.</p>
<pre name="code" class="php">
%some_hash = (key1=&gt;'val1', "some key with special chars"=&gt;$val2 );# basic hash population
%another = (0 =&gt; 'a',   # Key 0 with value 'a'
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;1 =&gt; 'b', # key 1 with value 'b'
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;2 =&gt; 'c');# key 3 with value 'c'
</pre>
<p>When printing a hash, keep in mind that unlike arrays, hashes do NOT keep their keys in the order they were assigned. Perl rearranges hash element orders to maximize performance. If you need to print your keys in a certain order, you will have to sort them when accessing. We&#8217;ll see scalar, array, and hash functions in the chapter <em>Gettin&#8217; jiggy wit it</em> further ahead.<br />
The simplest way to access a hash element is to call its key. We use { } to delimit hash keys.</p>
<pre name="code" class="php">
print %some_hash; # prints key1val1
print $some_hash{key1}; # prints val1
</pre>
<p>Note that we are accessing <em>one</em> element of the hash, and therefore using <em>$</em> to start the variable name. The <em>$</em> alone would be confused with a scalar variable $some_hash, so we have to use { } to delimit the key. You&#8217;ll get used to seeing this in your or other people&#8217;s code:</p>
<pre name="code" class="php">
$var = 'a scalar variable';
$var[0] = 'first element of array @var';
$var{key1} = 'an element of hash %var';
</pre>
<p>Although the 3 examples above start with <em>$var</em>, they are totally different things. Perl won&#8217;t get confused, and neither will you if you learn to look for [  and {  after a variable name.</p>
<p style="text-align:right;"><a href="http://usestrict.net/2008/10/07/perl-crash-course-arrays-and-lists/" target="_self">« Arrays and Lists</a> | <a href="http://usestrict.net/2008/10/05/perl-crash-course/" target="_self">TOC</a> | <a href="http://usestrict.net/2008/11/20/perl-crash-course-references-and-complex-data-structures-cds/">References and Complex Data Structures (CDS)</a> »</p>
]]></content:encoded>
			<wfw:commentRss>http://usestrict.net/2008/10/perl-crash-course-hashes/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Perl Crash Course: Arrays and Lists</title>
		<link>http://usestrict.net/2008/10/perl-crash-course-arrays-and-lists/</link>
		<comments>http://usestrict.net/2008/10/perl-crash-course-arrays-and-lists/#comments</comments>
		<pubDate>Tue, 07 Oct 2008 12:41:48 +0000</pubDate>
		<dc:creator>vinny</dc:creator>
				<category><![CDATA[Perl]]></category>
		<category><![CDATA[Perl Course Howto]]></category>

		<guid isPermaLink="false">http://usestrict.wordpress.com/?p=138</guid>
		<description><![CDATA[Arrays and Lists Sometimes working with one piece of data just isn&#8217;t enough. You might want to specify lists of data, and save those lists in a variable. For this purpose, Perl gives us the list and array constructs. Lists Lists are just that &#8211; a comma-separated list of data specified between parentheses. You can [...]]]></description>
			<content:encoded><![CDATA[<p><span style="font-size:18px;">Arrays and Lists</span></p>
<p>Sometimes working with <em>one</em> piece of data just isn&#8217;t enough. You might want to specify lists of data, and save those lists in a variable. For this purpose, Perl gives us the list and array constructs.</p>
<p><span id="more-17"></span></p>
<p><em><strong>Lists</strong></em></p>
<p>Lists are just that &#8211; a comma-separated list of data specified between parentheses. You can add as many pieces of data (strings, numbers, variables) to a list as your computer&#8217;s memory can hold. Here&#8217;s an example of a list:</p>
<pre name="code" class="php">
(1, 2, 'some string here', "hello $world", $myvar);   # plain list - not very useful though
</pre>
<p>As you can see in the example above, the elements in a list in Perl don&#8217;t have to contain the same kind of data like you&#8217;ll see in some other programming languages (only int&#8217;s, char&#8217;s, strings&#8230;). However, in the example above there isn&#8217;t much you can do with that list just the way it is. You&#8217;ll probably want to access its elements and assign it to variables:</p>
<pre name="code" class="php">
($num1,$num2,$string1,$string2,$a_var) = (1, 2, 'some string here', "hello $world", $myvar);
</pre>
<p>All the values of the list on the right have been assigned to the variables in the list on the left.  Now, suppose you don&#8217;t want the second element of the list on the right. You can use <em>undef</em> as a placeholder in the list on the left:</p>
<pre name="code" class="php">
($num1, undef, undef, $string2,undef) = (1, 2, 'some string here', "hello $world", $myvar); # only the first and fourth values are kept
</pre>
<p>That last <em>undef</em> wasn&#8217;t really necessary. That&#8217;s because if you assign one list to another, if the list on the right has more values than the list on the left, the exceeding values will be automatically trashed. The <em>undef</em>s in the middle, however, are required so you can get the fourth position.</p>
<p>[ad#middle_end]</p>
<p>For cases where you want only one element of a list, you can select an element of a list by placing its index between [ ] right after the closing ). Indexes in Perl start in 0 by default and are numbered from left to right. You can change the startup index value by setting the variable <em>$[</em>, but you don't want to do that unless you REALLY know what you're doing. To access the list elements from right to left, use negative indexes, starting at -1 for the right-most element, then -2 for the second to last, and so on.</p>
<pre name="code" class="php">
$some_var = (1, 2, 'some string here', "hello $world", $myvar)[0];    # $some_var now holds 1
$another_var = (1, 2, &#8216;some string here&#8217;, &#8220;hello $world&#8221;, $myvar)[-1]; # $another_var gets a copy of $myvar
$and_yet_another = (1, 2, &#8216;some string here&#8217;, &#8220;hello $world&#8221;, $myvar)[(2+2-1)*6-17]; # the crazy math evaluates to 1, so you get the second element of the list
</pre>
<p>To get more than one value of a list, you can use multiple indexes separated by commas:</p>
<pre name="code" class="php">
($num1,$string2) = (1, 2, 'some string here', "hello $world", $myvar)[0,3]; # only the first and fourth values are assigned
</pre>
<p>More about that in the chapter about <a href="http://usestrict.net/2009/02/01/perl-crash-course-gettin-jiggy-wit-it/">Slices</a>.</p>
<p>Now, suppose you need to use the same list over and over, and just don't feel like typing everything all the time. You need an Array.</p>
<p><strong><em>Arrays</em></strong></p>
<p>An array is the kind of variable that Perl gives you to keep your lists in. All array names start with @ (stylish <em>A</em> for <em>A</em>rray) and follow the same naming rules as scalars (except for the $ part).</p>
<pre name="code" class="php">
@some_array
@_another_array
@i
</pre>
<p>To assign a list to an array, just do it like you would a scalar. You can also use the range (..) operator:</p>
<pre name="code" class="php">
@colors = ('red', 'blue', 'yellow'); # assign @colors a list of 3 values
@ranges = (1..10,"a".."z","XX".."XZ"); # from 1 to 10, a to z, and XX to XZ
</pre>
<p>To access individual elements, use the same [ index ] construct:</p>
<pre name="code" class="php">
print $colors[0];  # prints out 'red' to the screen
</pre>
<p><em>Whoah - hold on a sec!!</em> You saw the $ instead of @ in the example above, right? The reason we did that is because we're accessing <em>one</em> element of the array, and as we saw in the Scalars chapter, <em>one</em> of anything is a scalar. And this is where some people get confused. You see, <em>$colors</em> and <em>$colors[0]</em> are 2 totally different things (there's yet a third element to this confusion, as you'll see when we get to Hashes).  The former is the scalar variable $colors, and the latter is the first element of the array @colors. To avoid mistakes while reading Perl code, be sure to check for any <em>[</em> or <em>{</em> (not there yet) after the variable name.</p>
<p>Here are some array operations that you can use:</p>
<pre name="code" class="php">
@copy_of_colors = @colors;  #  @copy_of_colors now contains 'red', 'blue', and 'yellow'
@reversed = reverse @copy_of_colors;  # yellow, 'blue', 'red'
$first_value = shift(@reversed); # $first_value gets 'yellow', and @reversed is left with 'blue', and 'red' only
</pre>
<p>The <em>$#</em> construct allows you to access the last index value of the array. E.g.: For our <em>@colors</em> array, we would get value 2 (indexes start with 0, right?) for $#colors (again, <em>$#colors</em> starts with a <em>$</em> because it's <em>one</em> value). This being said, another form of accessing the last element of any value is to do this:</p>
<pre name="code" class="php">
$last_element = $colors[$#colors]; # same as $colors[2]
</pre>
<p>We will get deeper into scalar and array functions when we reach <em>Gettin' jiggy wit it</em>.</p>
<p><strong><em>Context</em></strong></p>
<p>One very important thing you MUST know and understand is that Perl treats arrays according to context. There is scalar context and list context. They can be <strong>implicit</strong> or <strong>explicit</strong>. This is how it works:</p>
<pre name="code" class="php">
@colors = ('red', 'yellow', 'blue');   # set up the @colors array
$count = @colors;  # count now holds number 3, because @colors has 3 elements
$count = scalar(@colors);  # same thing, but called explicitly
</pre>
<p>When we assigned <em>@colors</em> to <em>$count</em>, since <em>$count</em> is a scalar, Perl understood that we're talking in scalar context. When you call an array in scalar context, you'll get the number of elements inside that array.</p>
<p>If you need to print out an entire array, there is also a small catch:</p>
<pre name="code" class="php">
print @colors;  # prints out 'redyellowblue'
print "@colors";  # prints out 'red yellow blue'
print '@colors';  # prints out '@colors' - no interpolation with single quotes, remember?
</pre>
<p>[ad#middle_end]</p>
<p style="text-align:right;"><a href="http://usestrict.net/2008/10/06/perl-crash-course-scalars/" target="_self">« Scalars</a> | <a href="http://usestrict.net/2008/10/05/perl-crash-course/" target="_self">TOC</a> | <a href="http://usestrict.net/2008/10/31/perl-crash-course-hashes/">Hashes</a> »</p>
]]></content:encoded>
			<wfw:commentRss>http://usestrict.net/2008/10/perl-crash-course-arrays-and-lists/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Perl Crash Course: Scalars</title>
		<link>http://usestrict.net/2008/10/perl-crash-course-scalars/</link>
		<comments>http://usestrict.net/2008/10/perl-crash-course-scalars/#comments</comments>
		<pubDate>Mon, 06 Oct 2008 03:22:15 +0000</pubDate>
		<dc:creator>vinny</dc:creator>
				<category><![CDATA[Perl]]></category>
		<category><![CDATA[Perl Course Howto]]></category>

		<guid isPermaLink="false">http://usestrict.wordpress.com/?p=121</guid>
		<description><![CDATA[Scalars Variable Names Scalar is the type of variable used to hold one single piece of information. Examples of scalar information are one string, one character, one object, one reference&#8230; If you can say one something, then it&#8217;s scalar. All scalar variables start with $ and a letter or underscore. As we will see in [...]]]></description>
			<content:encoded><![CDATA[<p><span style="font-size:18px;">Scalars</span></p>
<p><em><strong>Variable Names</strong></em></p>
<p>Scalar is the type of variable used to hold one single piece of information. Examples of scalar information are <em>one</em> string, <em>one</em> character, <em>one</em> object, <em>one </em>reference&#8230; If you can say <em>one</em> something, then it&#8217;s scalar.</p>
<p><span id="more-15"></span></p>
<p>All scalar variables start with <em>$</em> and a letter or underscore. As we will see in the Regular Expressions chapter, there can be variables such as $1, $2, etc. but they are reserved by the system. $0 also exists and keeps the name of the script. The size of variable names is limited only by your imagination and common sense.</p>
<pre name="code" class="php">
$var
$_thisName
$a_really_big_and_annoying_variable_name
</pre>
<p><strong><em>Quoting, Escaping, and Interpolation</em></strong></p>
<p>When assigning a string to a variable, you can include other variables and count on getting their values. This is called interpolation, and can be achieved by using double quotes (&#8221;  &#8220;) around your string.</p>
<pre name="code" class="php">
$name = 'Vinny';
$some_string = "My name is $namen"; # My name is Vinny
</pre>
<p>In the previous example, Perl sees that we are using double quotes, and also sees that there is a variable (<em>$name</em>) inside the string. So first it replaces the variable with its value and then assigns the interpolated string to the variable named <em>$some_string</em>.</p>
<p>Had we tried the previous example with single quotes, the result would have been literally <em>My name is $name</em>. Note that we also added a &#8220;n&#8221; in our double-quoted example, which means to go to the next line. Newline characters (n), as well as everything else is interpreted literally when using single quotes.</p>
<p>Interpolation can be tricky at times when we want no spaces between our variable and some part of the string, or when we want to print a variable name within a double-quoted string. The solution for this is the &#8220;&#8221; (backslash), which we saw just above. Backslashes are used for escaping and giving special meanings to certain characters.</p>
<p>For example:</p>
<pre name="code" class="php">
$some_string = "My name is $namen"; # My name is $namen
</pre>
<p>Since there&#8217;s a backslash just before <em>$</em>, it tells Perl to NOT replace the variable $name with its value. It&#8217;s simply using the literal variable name. We could have achieved just about the same results if we had surrounded the string in single quotes, with the drawback of having a literal n at the end of our string:</p>
<p>If you need to use a single quote inside a single-quoted string, you can escape it with the backslash as well:</p>
<pre name="code" class="php">
$hello = 'Welcome to usestrict's Perl Crash Course';
</pre>
<p>Follows a list of Perl&#8217;s backslashed character escapes:</p>
<table style="height:247px;" border="1" width="399">
<tbody>
<tr>
<th>Code</th>
<th>Meaning</th>
</tr>
<tr>
<td><tt>n</tt></td>
<td>Newline (usually LF)</td>
</tr>
<tr>
<td><tt>r</tt></td>
<td>Carriage return (usually CR)</td>
</tr>
<tr>
<td><tt>t</tt></td>
<td>Horizontal tab</td>
</tr>
<tr>
<td><tt>f</tt></td>
<td>Form feed</td>
</tr>
<tr>
<td><tt>b</tt></td>
<td>Backspace</td>
</tr>
<tr>
<td><tt>a</tt></td>
<td>Alert (bell)</td>
</tr>
<tr>
<td><tt>e</tt></td>
<td>ESC character</td>
</tr>
<tr>
<td><tt>33</tt></td>
<td>ESC in octal</td>
</tr>
<tr>
<td><tt>x7f</tt></td>
<td>DEL in hexadecimal</td>
</tr>
<tr>
<td><tt>cC</tt></td>
<td>Control-C</td>
</tr>
<tr>
<td><tt>x{263a}</tt></td>
<td>Unicode (smiley)</td>
</tr>
</tbody>
</table>
<p>Perl provides us with some handy constructs that allow us to quote strings or individual words without having to worry (much) about escaping special characters. They are:</p>
<pre name="code" class="php">
q/some literal string/; # does not interpolate
qq/some interpolated string/; # you guessed it - interpolations galore
qx/ls -la */; # executes the command between /  /
</pre>
<p>There are more, which I will explain when we reach Arrays and Regular expressions.</p>
<p>It&#8217;s interesting to note that these quoting constructs don&#8217;t necessarily have to delimit the quoted subject with /  /. You can choose just about any character you&#8217;d like, as long as you follow the simple rule of using the matching closing character for any of [, {, or (. For all other characters, you just need to use the same one used to open the quotes.</p>
<pre name="code" class="php">
q[some literal string];
q{another literal string};
q|one more literal string|;
q#I can even use pound characters!#;
</pre>
<p><strong>Concatenation</strong></p>
<p>Sometimes you may want to separate a string into two different pieces, one with each kind of quoting. You can do that with concatenations. Concatenations are represented by . (dot).</p>
<pre name="code" class="php">
$some_string = 'This is a concatenated string' . "n";
</pre>
<p>In the example above, we concatenate a single quoted-string with a newline within double quotes. Another form to concatenate strings is through the <strong>.=</strong> (concat and assign) operator. The example above could also be written like this:</p>
<pre name="code" class="php">
$some_string = 'This is a concatenated string';
$some_string .= "n";
</pre>
<p><strong><em>Numbers</em></strong></p>
<p>Like any other programming language, Perl also holds numbers. It can hold numbers in decimal, hexadecimal, binary, or octal notation.</p>
<pre name="code" class="php">
$a_dec_number = 1;  # your every day number 1
$a_hex_number = 0x1; # number 1 in hex notation
$a_oct_number = 01; # number 1 in octal
$a_bin_number = 0b1; # number 1 in binary
</pre>
<p>Unlike most other languages, however, you can treat numbers as strings and get away with it.</p>
<pre name="code" class="php">
$var1 = '1'; # you can use single quotes
$var2 = "2"; # or double quotes - Perl doesn't care
print $var1 + $var2; # prints out 3
</pre>
<p>Just like we have <em>.=</em> to concatenate strings, there are similar operators for numbers. They are:</p>
<table border="1" width="80%">
<tr>
<td>
<strong>Operator</strong>
</td>
<td>
<strong>Function</strong>
</td>
</tr>
<tr>
<td>
 +=
</td>
<td>
Add and Assign
</td>
</tr>
<tr>
<td>
 -=
</td>
<td>
Subtract and Assign
</td>
</tr>
<tr>
<td>
 /=
</td>
<td>
Divide and Assign
</td>
</tr>
<tr>
<td>
 *=
</td>
<td>
Multiply and Assign
</td>
</tr>
</table>
<p>Example:</p>
<pre name="code" class="php">
$i = 1; # <em>$i</em> is initiated with 1
$i += 5; # <em>$i</em> is now 6
</pre>
<p>Lastly, there are the <em><strong>auto-increment</strong></em> and <em><strong>auto-decrement</strong></em> operators: <strong>++</strong> and <strong>- -</strong>. They can be used either preceding or following the variable name.</p>
<pre name="code" class="php">
$i++; # <em>$i</em> is now 7
$i--; # back to 6
++$i;# 7 again
--$i; # 6 once more
</pre>
<p>The difference between $i++ and ++$i is that the former returns the original value and then increments, while the latter first increments and then returns. The same goes for decrements. We can see this at work if we do a print:</p>
<pre name="code" class="php">
print $i++ ; # prints 6
print $i; # prints 7 because of the previous increment
print ++$i; # prints 8, since it incremented before printing
print $i; # prints 8 again - no change after the previous increment
</pre>
<p><em><strong>Empty or Undefined?</strong></em></p>
<p>When you want variable to have no value, you can choose to either set it to an empty string (''  or "")  or assign it the <em>undef</em> value.</p>
<pre name="code" class="php">
$some_var = '';  # 2 single quotes with nothing inside
$variant = ""; # 2 double quotes with nothing inside
$other_var = undef; # using undef
</pre>
<p>We'll see <em>undef</em> further along the course, and understand what role it plays in boolean functions.</p>
<p style="text-align:right;"><a href="http://usestrict.net/2008/10/06/perl-crash-course-variables-and-data-structures/" target="_self">« Variables and Data Structures</a> | <a href="http://usestrict.net/2008/10/05/perl-crash-course/" target="_self">TOC</a> | <a href="http://usestrict.net/2008/10/07/perl-crash-course-arrays-and-lists/">Arrays and Lists »</a></p>
]]></content:encoded>
			<wfw:commentRss>http://usestrict.net/2008/10/perl-crash-course-scalars/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Perl Crash Course: Variables and Data Structures</title>
		<link>http://usestrict.net/2008/10/perl-crash-course-variables-and-data-structures/</link>
		<comments>http://usestrict.net/2008/10/perl-crash-course-variables-and-data-structures/#comments</comments>
		<pubDate>Mon, 06 Oct 2008 03:18:53 +0000</pubDate>
		<dc:creator>vinny</dc:creator>
				<category><![CDATA[Perl]]></category>
		<category><![CDATA[Perl Course Howto]]></category>

		<guid isPermaLink="false">http://usestrict.wordpress.com/?p=95</guid>
		<description><![CDATA[In this chapter, we will see the three types of variables available in Perl: Scalars, Arrays, and Hashes. We will also work with lists, slices, and Complex Data Structures. However, before we go on, you will need to know a few basic commands so you understand the examples. Code comments: In Perl, you can add [...]]]></description>
			<content:encoded><![CDATA[<p>In this chapter, we will see the three types of variables available in Perl: Scalars, Arrays, and Hashes. We will also work with lists, slices, and Complex Data Structures. However, before we go on, you will need to know a few basic commands so you understand the examples.</p>
<p><span style="text-decoration:underline;"><em>Code comments:</em></span> In Perl, you can add comments to the code by using the character #. Whatever is to the right of a # will not be parsed (with at least one exception: the <em>$#array</em> structure which we will see later in the Arrays section). You may find it annoying to not have /*  */ structure for multi-line comments, but you&#8217;ll be happy to know that you can emulate multi-line comments using POD, which we&#8217;ll see later on.</p>
<p><span style="text-decoration:underline;"><em>Printing:</em></span> Perl prints to the screen through the command <em>print</em>, which takes a list of parameters as input.</p>
<p><span style="text-decoration:underline;"><em>Assigning:</em></span> To assign values to a variable, use  <strong><em>=</em></strong> (the equals operator).</p>
<p><span style="text-decoration:underline;"><em>Statement separator:</em></span> Every statement in Perl ends with <strong><em>;</em></strong> (semi-colon). Failure to end a statement with <em>; </em>will result in a syntax error when trying to run your script.</p>
<p><span style="text-decoration:underline;"><em>Math:</em></span> Mathematical operators are <strong>+</strong>, <strong>-</strong>, <strong>*</strong>, <strong>/</strong>, and <strong>%</strong>, for addition, subtraction, multiplication, division, and modulus &#8211; respectively. The modulus operator returns the remainder of a division.</p>
<p>Now on to the scalars&#8230;</p>
<p style="text-align:right;"><a href="http://usestrict.net/2008/10/05/perl-crash-course-getting-it-installed-on/" target="_self">« Getting it installed on&#8230;</a> | <a href="http://usestrict.net/2008/10/05/perl-crash-course/" target="_self">TOC</a> | <a href="http://usestrict.net/2008/10/06/perl-crash-course-scalars/" target="_self">Scalars »</a></p>
]]></content:encoded>
			<wfw:commentRss>http://usestrict.net/2008/10/perl-crash-course-variables-and-data-structures/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

