1. Shlomi Fish
  2. perl-begin

Source

perl-begin / lib / tutorials / modern-perl / xhtml / chapter_01.html

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta name="generator" content="HTML Tidy for Linux (vers 25 March 2009), see www.w3.org" />
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="../styles/style.css" type="text/css" />
</head>
<body>
<h1 id="heading_id_2">The Perl Philosophy</h1>
<p>Perl gets things done--it's flexible, forgiving, and malleable. Capable programmers use it every day for everything from one-liners and one-off automations to multi-year, multi-programmer projects.</p>
<p>Perl is pragmatic. You're in charge. You decide how to solve your problems and Perl will mold itself to do what you mean, with little frustration and no ceremony.</p>
<p>Perl will grow with you. In the next hour, you'll learn enough to write real, useful programs--and you'll understand <em>how</em> the language works and <em>why</em> it works as it does. Modern Perl takes advantage of this knowledge and the combined experience of the global Perl community to help you write working, maintainable code.</p>
<p>First, you need to know how to learn more.</p>
<h2 id="heading_id_3">Perldoc</h2>
<div id="perldoc"></div>
<div id="iperldoc_0"></div>
<p>Perl has a culture of useful documentation. The <code>perldoc</code> utility is part of every complete Perl 5 installation <span class="footnote">(footnote: However your Unix-like system may require you to install an additional package such as <code>perl-doc</code> on Debian or Ubuntu GNU/Linux.)</span>. <code>perldoc</code> displays the documentation of every Perl module installed on the system--whether a core module or one installed from the Comprehensive Perl Archive Network (CPAN)--as well as thousands of pages of Perl's copious core documentation.</p>
<div class="sidebar">
<div id="iCPAN_0"></div>
<div id="imetacpan_0"></div>
<p><span class="url">http://perldoc.perl.org/</span> hosts recent versions of the Perl documentation. CPAN indexes at <span class="url">http://search.cpan.org/</span> and <span class="url">http://metacpan.org/</span> provide documentation for all CPAN modules. Other Perl 5 distributions such as ActivePerl and Strawberry Perl provide local documentation in HTML formats.</p>
</div>
<p>Use <code>perldoc</code> to read the documentation for a module or part of the core documentation:</p>
<div class="screen">
<pre>
<code>    $ <strong>perldoc List::Util</strong>
    $ <strong>perldoc perltoc</strong>
    $ <strong>perldoc Moose::Manual</strong></code>
</pre></div>
<p>The first example displays the documentation embedded within the <code>List::Util</code> module. The second example displays a pure documentation file, in this case the table of contents of the core documentation. The third example displays a pure documentation file included as part of a CPAN distribution (<a href="chapter_07.html#moose">Moose</a>(moose)). <code>perldoc</code> hides these details; there's no distinction between reading the documentation for a core library such as <code>Data::Dumper</code> or one installed from the CPAN.</p>
<p>The standard documentation template includes a description of the module, demonstrates sample uses, and then contains a detailed explanation of the module and its interface. While the amount of documentation varies by author, the form of the documentation is remarkably consistent.</p>
<div class="tip">
<p><code>perldoc perltoc</code> displays the table of contents of the core documentation, and <code>perldoc perlfaq</code> displays the table of contents for Frequently Asked Questions about Perl 5. <code>perldoc perlop</code> and <code>perldoc perlsyn</code> document Perl's symbolic operators and syntactic constructs. <code>perldoc perldiag</code> explains the meanings of Perl's warning messages. <code>perldoc perlvar</code> lists all of Perl's symbolic variables. Skimming these files will give you a great overview of Perl 5.</p>
</div>
<div id="iperldoc__i45q_40search_perlfaq41_0"></div>
<p>The <code>perldoc</code> utility has many more abilities (see <code>perldoc perldoc</code>). The <code>-q</code> option searches only the Perl FAQ for any provided keywords. Thus <code>perldoc -q sort</code> returns three questions: <em>How do I sort an array by (anything)?</em>, <em>How do I sort a hash (optionally by value instead of key)?</em>, and <em>How can I always keep my hash sorted?</em>.</p>
<div id="iperldoc__i45f_40search_perlfunc41_0"></div>
<p>The <code>-f</code> option displays the documentation for a builtin Perl function. <code>perldoc -f sort</code> explains the behavior of the <code>sort</code> operator. If you don't know the name of the function you want, browse the list of available builtins in <code>perldoc perlfunc</code>.</p>
<div id="iperldoc__i45v_40search_perlvar41_0"></div>
<p>The <code>-v</code> option looks up a builtin variable. For example, <code>perldoc -v $PID</code> displays the documentation for the variable which contains the current program's process id. Depending on your shell, you may have to quote the variable appropriately.</p>
<p>The <code>-l</code> option causes <code>perldoc</code> to display the <em>path</em> to the documentation file rather than the contents of the documentation <span class="footnote">(footnote: Be aware that a module may have a separate <em>.pod</em> file in addition to its <em>.pm</em> file.)</span>.</p>
<p>The <code>-m</code> option displays the entire <em>contents</em> of the module, code and all, without performing any special formatting.</p>
<div id="iPOD_0"></div>
<div id="iPOD__iperldoc_0"></div>
<div id="iPOD__ipodchecker_0"></div>
<div id="iPOD__iPod5858Webserver_0"></div>
<div id="iCPAN__iPod5858Webserver_0"></div>
<p>Perl 5's documentation system is <em>POD</em>, or <em>Plain Old Documentation</em>. <code>perldoc perlpod</code> describes how POD works. Other POD tools include <code>podchecker</code>, which validates the form of your POD, and <code>Pod::Webserver</code>, which displays local POD as HTML through a minimal web server.</p>
<h2 id="heading_id_4">Expressivity</h2>
<div id="expressivity"></div>
<div id="iWall44_Larry_0"></div>
<div id="iLarry_Wall_0"></div>
<p>Larry Wall's studies of linguistics and human languages influenced the design of Perl. The language allows you tremendous freedom to solve your problems, depending on your group style, the available time, the expected lifespan of the program, or even how creative you feel. You may write simple, straightforward code or integrate into larger, well-defined programs. You may select from multiple design paradigms, and you may eschew or embrace advanced features.</p>
<p>Where other languages enforce one best way to write any code, Perl allows <em>you</em> to decide what's most readable or useful or fun.</p>
<div id="iTIMTOWTDI_0"></div>
<div id="iTim_Toady_0"></div>
<p>Perl hackers have a slogan for this: <em>TIMTOWTDI</em>, pronounced "Tim Toady", or "There's more than one way to do it!"</p>
<p>Though this expressivity allows master craftworkers to create amazing programs, it allows the unwise or uncautious to make messes. Experience and good taste will guide you to write great code. The choice is yours--but be mindful of readability and maintainability, especially for those who come after you.</p>
<p>Perl novices often may find certain constructs opaque. Many of these idioms (<a href="chapter_10.html#idioms">Idioms</a>(idioms)) offer great (if subtle) power. It's okay to avoid them until you're comfortable with them.</p>
<p>Learning Perl is like learning a new spoken language. You'll learn a few words, string together sentences, and soon will enjoy simple conversations. Mastery comes with practice of reading and writing. You don't have to understand every detail of Perl to be productive, but the principles in this chapter are vital to your growth as a programmer.</p>
<p>As another design goal, Perl tries to avoid surprising experienced (Perl) programmers. For example, adding two variables (<code>$first_num + $second_num</code>) is obviously a numeric operation (<a href="chapter_04.html#numeric_operators">Numeric Operators</a>(numeric_operators)); the addition operator must treat both as numeric values to produce a numeric result. No matter the contents of <code>$first_num</code> and <code>$second_num</code>, Perl will coerce them to numeric values (<a href="chapter_03.html#numeric_coercion">Numeric Coercion</a>(numeric_coercion)). You've expressed your intent to treat them as numbers by using a numeric operator. Perl happily does so.</p>
<div id="iDWIM_0"></div>
<div id="iprinciple_of_least_astonishment_0"></div>
<p>Perl adepts often call this principle <em>DWIM</em>, or <em>do what I mean</em>. Another phrasing is that Perl follows the <em>principle of least astonishment</em>. Given a cursory understanding of Perl (especially context; <a href="chapter_01.html#context_philosophy">Context</a>(context_philosophy)), it should be possible to understand the intent of an unfamiliar Perl expression. You will develop this skill.</p>
<div id="ibaby_Perl_0"></div>
<p>Perl's expressivity also allows novices to write useful programs without having to understand everything. The resulting code is often called <em>baby Perl</em>, in the sense that most everyone wants to help babies learn to communicate well. Everyone begins as a novice. Through practice and learning from more experienced programmers, you will understand and adopt more powerful idioms and techniques.</p>
<p>For example, an experienced Perl hacker might triple a list of numbers with:</p>
<div class="programlisting">
<pre>
<code>    my @tripled = map { $_ * 3 } @numbers;</code>
</pre></div>
<p>... and a Perl adept might write:</p>
<div class="programlisting">
<pre>
<code>    my @tripled;

    for my $num (@numbers)
    {
        push @tripled, $num * 3;
    }</code>
</pre></div>
<p>... while a novice might try:</p>
<div class="programlisting">
<pre>
<code>    my @tripled;

    for (my $i = 0; $i &lt; scalar @numbers; $i++)
    {
        $tripled[$i] = $numbers[$i] * 3;
    }</code>
</pre></div>
<p>All three approaches accomplish the same thing, but each uses Perl in a different way.</p>
<p>Experience writing Perl will help you to focus on <em>what</em> you want to do rather than <em>how</em> to do it. Even so, Perl will happily run simple programs. You can design and refine your programs for clarity, expressivity, reuse, and maintainability, in part or in whole. Take advantage of this flexibility and pragmatism: it's far better to accomplish your task effectively now than to write a conceptually pure and beautiful program next year.</p>
<h2 id="heading_id_5">Context</h2>
<div id="context_philosophy"></div>
<div id="icontext_0"></div>
<p>In spoken languages, the meaning of a word or phrase may depend on how you use it; the local <em>context</em> helps clarify the intent. For example, the inappropriate pluralization of "Please give me one hamburgers!" <span class="footnote">(footnote: The pluralization of the noun differs from the amount.)</span> sounds wrong, just as the incorrect gender of "la gato" <span class="footnote">(footnote: The article is feminine, but the noun is masculine.)</span> makes native speakers chuckle. Consider also the pronoun "you" or the noun "sheep" which can be singular or plural depending on context.</p>
<p>Context in Perl is similar. It governs the amount as well as the kind of data to use. Perl will happily attempt to provide exactly what you ask for--provided you do so by choosing the appropriate context.</p>
<p>Certain Perl operations produce different behaviors when you want zero, one, or many results. A specific construct in Perl may do something different if you write "Do this, but I don't care about any results" compared to "Do this, and I expect multiple results." Other operations allow you to specify whether you expect to work with numeric data, textual data, or true or false data.</p>
<p>Context can be tricky if you try to write or read Perl code as a series of single expressions extracted from their environments. You may find yourself slapping your forehead after a long debugging session when you discover that your assumptions about context were incorrect. If instead you're cognizant of context, your code will be more correct--and cleaner, flexible, and more concise.</p>
<h3 id="heading_id_6">Void, Scalar, and List Context</h3>
<div id="amount_context"></div>
<div id="icontext__iamount_0"></div>
<div id="iamount_context_0"></div>
<p><em>Amount context</em> context governs <em>how many</em> items you expect from an operation. The English language's subject-verb number agreement is a close parallel. Even without knowing the formal description of this linguistic principle, you probably understand the error in the sentence "Perl are a fun language". In Perl, the number of items you request determines how many you get.</p>
<div id="ivoid_context_0"></div>
<div id="icontext__ivoid_0"></div>
<p>Suppose you have a function (<a href="chapter_05.html#functions">Declaring Functions</a>(functions)) called <code>find_chores()</code> which sorts your household todo list in order of task priority. The means by which you call this function determines what it will produce. You may have no time to do chores, in which case calling the function is an attempt to look industrious. You may have enough time to do one task, or you could have a burst of energy on a free weekend and desire to accomplish as much as possible.</p>
<p>If you call the function on its own and never use its return value, you've called the function in <em>void context</em>:</p>
<div class="programlisting">
<pre>
<code>    find_chores();</code>
</pre></div>
<div id="icontext__iscalar_0"></div>
<div id="iscalar_context_0"></div>
<p>Assigning the function's return value to a single item (<a href="chapter_03.html#scalars">Scalars</a>(scalars)) evaluates the function in <em>scalar context</em>:</p>
<div class="programlisting">
<pre>
<code>    my $single_result = find_chores();</code>
</pre></div>
<div id="ilist_context_0"></div>
<div id="icontext__ilist_0"></div>
<p>Assigning the results of calling the function to an array (<a href="chapter_03.html#arrays">Arrays</a>(arrays)) or a list, or using it in a list, evaluates the function in <em>list context</em>:</p>
<div class="programlisting">
<pre>
<code>    my @all_results             = find_chores();
    my ($single_element, @rest) = find_chores();
    process_list_of_results( find_chores() );</code>
</pre></div>
<p>The parentheses in the second line of the previous example group the two variable declarations (<a href="chapter_05.html#lexical_scope">Lexical Scope</a>(lexical_scope)) so that assignment will behave as you expect. If <code>@rest</code> were to go unused, you could also correctly write:</p>
<div class="programlisting">
<pre>
<code>    my <strong>(</strong>$single_element<strong>)</strong>   = find_chores();</code>
</pre></div>
<p>.... in which case the parentheses give a hint to the Perl 5 parser that you intend list context for the assignment even though you assign only one element of a list. This is subtle, but now that you know about it, the difference of amount context between these two statements should be obvious:</p>
<div class="programlisting">
<pre>
<code>    my $scalar_context = find_chores();
    my <strong>(</strong>$list_context<strong>)</strong> = find_chores();</code>
</pre></div>
<p>Evaluating a function or expression--except for assignment--in list context can produce confusion. Lists propagate list context to the expressions they contain. Both of these calls to <code>find_chores()</code> occur in list context:</p>
<div class="programlisting">
<pre>
<code>    process_list_of_results( find_chores() );

    my %results =
    (
        cheap_operation     =&gt; $cheap_results,
        expensive_operation =&gt; find_chores(), # OOPS!
    );</code>
</pre></div>
<div id="ibuiltins__iscalar_0"></div>
<p>The latter example often surprises novice programmers, as initializing a hash (<a href="chapter_03.html#hashes">Hashes</a>(hashes)) with a list of values imposes list context on <code>find_chores</code>. Use the <code>scalar</code> operator to impose scalar context:</p>
<div class="programlisting">
<pre>
<code>    my %results =
    (
        cheap_operation     =&gt; $cheap_results,
        expensive_operation =&gt; <strong>scalar</strong> find_chores(),
    );</code>
</pre></div>
<p>Why does context matter? A context-aware function can examine its calling context and decide how much work it must do. In void context, <code>find_chores()</code> may legitimately do nothing. In scalar context, it can find only the most important task. In list context, it must sort and return the entire list.</p>
<h3 id="heading_id_7">Numeric, String, and Boolean Context</h3>
<div id="value_contexts"></div>
<div id="ivalue_context_0"></div>
<div id="icontext__ivalue_0"></div>
<p>Perl's other context--<em>value context</em>--governs how Perl interprets a piece of data. You've probably already noticed that Perl's flexible about figuring out if you have a number or a string and converting between the two as you want them. In exchange for not having to declare (or at least track) explicitly what <em>type</em> of data a variable contains or a function produces, Perl's type contexts provide hints that tell the compiler how to treat data.</p>
<div id="ibuiltins__ieq_0"></div>
<p>Perl will coerce values to specific proper types (<a href="chapter_03.html#coercion">Coercion</a>(coercion)), depending on the operators you use. For example, the <code>eq</code> operator tests that strings contain the same information <em>as strings</em>:</p>
<div class="programlisting">
<pre>
<code>    say "Catastrophic crypto fail!" if $alice eq $bob;</code>
</pre></div>
<p>You may have had a baffling experience where you <em>know</em> that the strings are different, but they still compare the same:</p>
<div class="programlisting">
<pre>
<code>    my $alice = 'alice';
    say "Catastrophic crypto fail!" if $alice == 'Bob';</code>
</pre></div>
<div id="istring_context_0"></div>
<div id="inumeric_context_0"></div>
<div id="icontext__istring_0"></div>
<div id="icontext__inumeric_0"></div>
<div id="ibuiltins__i6161_0"></div>
<p>The <code>eq</code> operator treats its operands as strings by enforcing <em>string context</em> on them. The <code>==</code> operator imposes <em>numeric context</em>. In numeric context, both strings evaluate to <code>0</code> (<a href="chapter_03.html#numeric_coercion">Numeric Coercion</a>(numeric_coercion)). Be sure to use the proper operator for the type of context you want.</p>
<div id="iboolean_context_0"></div>
<div id="icontext__iboolean_0"></div>
<p><em>Boolean context</em> occurs when you use a value in a conditional statement. In the previous examples, <code>if</code> evaluated the results of the <code>eq</code> and <code>==</code> operators in boolean context.</p>
<div id="icontext__iexplicit_0"></div>
<p>In rare circumstances, you may need to force an explicit context where no appropriately typed operator exists. To force a numeric context, add zero to a variable. To force a string context, concatenate a variable with the empty string. To force a boolean context, double the negation operator:</p>
<div class="programlisting">
<pre>
<code>    my $numeric_x =  0 + $x;  # forces numeric context
    my $stringy_x = '' . $x;  # forces string  context
    my $boolean_x =    !!$x;  # forces boolean context</code>
</pre></div>
<p>Type contexts are easier to identify than amount contexts. Once you know which operators provide which contexts (<a href="chapter_04.html#operator_types">Operator Types</a>(operator_types)), you'll rarely make mistakes.</p>
<h2 id="heading_id_8">Implicit Ideas</h2>
<div id="implicit_ideas"></div>
<p>Context is only one linguistic shortcut in Perl. Programmers who understand these shortcuts can glance at code and instantly understand its most important characteristics. Another important linguistic feature is the Perl equivalent of pronouns.</p>
<h3 id="heading_id_9">The Default Scalar Variable</h3>
<div id="default_scalar_variable"></div>
<div id="idefault_variables__iscalar_0"></div>
<div id="idefault_variables__i36__0"></div>
<div id="ivariables__i36__0"></div>
<div id="i36___idefault_scalar_variable_0"></div>
<p>The <em>default scalar variable</em> (also called the <em>topic variable</em>), <code>$_</code>, is most notable in its <em>absence</em>: many of Perl's builtin operations work on the contents of <code>$_</code> in the absence of an explicit variable. You can still use <code>$_</code> as the variable, but it's often unnecessary.</p>
<div id="ibuiltins__ichomp_0"></div>
<div id="ibuiltins__ichr_0"></div>
<div id="ibuiltins__iord_0"></div>
<div id="ibuiltins__ilc_0"></div>
<div id="ibuiltins__ilength_0"></div>
<div id="ibuiltins__ireverse_0"></div>
<div id="ibuiltins__iuc_0"></div>
<p>Many of Perl's scalar operators (including <code>chr</code>, <code>ord</code>, <code>lc</code>, <code>length</code>, <code>reverse</code>, and <code>uc</code>) work on the default scalar variable if you do not provide an alternative. For example, the <code>chomp</code> builtin removes any trailing newline sequence from its operand <span class="footnote">(footnote: See <code>perldoc -f chomp</code> and <code>$/</code> for more precise details of its behavior.)</span>:</p>
<div class="programlisting">
<pre>
<code>    my $uncle = "Bob\n";
    chomp $uncle;
    say "'$uncle'";</code>
</pre></div>
<p><code>$_</code> has the same function in Perl as the pronoun <em>it</em> in English. Without an explicit variable, <code>chomp</code> removes the trailing newline sequence from <code>$_</code>. Perl understands what you mean when you say "<code>chomp</code>"; Perl will always chomp <em>it</em>, so these two lines of code are equivalent:</p>
<div class="programlisting">
<pre>
<code>    chomp $_;
    chomp;</code>
</pre></div>
<div id="ibuiltins__isay_0"></div>
<div id="ibuiltins__iprint_0"></div>
<p>Similarly, <code>say</code> and <code>print</code> operate on <code>$_</code> in the absence of other arguments:</p>
<div class="programlisting">
<pre>
<code>    print;  # prints $_ to the current filehandle
    say;    # prints "$_\n" to the current filehandle</code>
</pre></div>
<div id="is474747__isubstitution_operator_0"></div>
<div id="im4747__imatch_operator_0"></div>
<div id="itr4747__itransliteration_operator_0"></div>
<p>Perl's regular expression facilities (<a href="chapter_06.html#regex">Regular Expressions and Matching</a>(regex)) default to <code>$_</code> to match, substitute, and transliterate:</p>
<div class="programlisting">
<pre>
<code>    $_ = 'My name is Paquito';
    say if /My name is/;

    s/Paquito/Paquita/;

    tr/A-Z/a-z/;
    say;</code>
</pre></div>
<div id="ibuiltins__ifor_0"></div>
<p>Perl's looping directives (<a href="chapter_03.html#looping_directives">Looping Directives</a>(looping_directives)) default to using <code>$_</code> as the iteration variable. Consider <code>for</code> iterating over a list:</p>
<div class="programlisting">
<pre>
<code>    say "#<strong>$_</strong>" for 1 .. 10;

    for (1 .. 10)
    {
        say "#<strong>$_</strong>";
    }</code>
</pre></div>
<div id="ibuiltins__iwhile_0"></div>
<p>... or <code>while</code>:</p>
<div class="programlisting">
<pre>
<code>    while (&lt;STDIN&gt;)
    {
        chomp;
        say scalar reverse;
    }</code>
</pre></div>
<div id="ibuiltins__imap_0"></div>
<p>... or <code>map</code> transforming a list:</p>
<div class="programlisting">
<pre>
<code>    my @squares = map { <strong>$_</strong> * <strong>$_</strong> } 1 .. 10;
    say for @squares;</code>
</pre></div>
<div id="ibuiltins__igrep_0"></div>
<p>... or <code>grep</code> filtering a list:</p>
<div class="programlisting">
<pre>
<code>    say 'Brunch time!'
        if grep { /pancake mix/ } @pantry;</code>
</pre></div>
<p>As English gets confusing when you have too many pronouns and antecedents, you must take care mixing uses of <code>$_</code> implicitly or explicitly. Uncautious simultaneous use of <code>$_</code> may lead to one piece of code silently overwriting the value written by another. If you write a function which uses <code>$_</code>, you may clobber a caller function's use of <code>$_</code>.</p>
<p>As of Perl 5.10, you may declare <code>$_</code> as a lexical variable (<a href="chapter_05.html#lexical_scope">Lexical Scope</a>(lexical_scope)) to prevent this clobbering behavior:</p>
<div class="programlisting">
<pre>
<code>    while (&lt;STDIN&gt;)
    {
        chomp;

        # BAD EXAMPLE
        my $munged = calculate_value( $_ );
        say "Original: $_";
        say "Munged  : $munged";
    }</code>
</pre></div>
<p>If <code>calculate_value()</code> or any other function changed <code>$_</code>, that change would persist through that iteration of the loop. Adding a <code>my</code> declaration prevents clobbering an existing instance of <code>$_</code>:</p>
<div class="programlisting">
<pre>
<code>    while (my $_ = &lt;STDIN&gt;)
    {
        ...
    }</code>
</pre></div>
<p>Of course, using a named lexical can be just as clear:</p>
<div class="programlisting">
<pre>
<code>    while (my $line = &lt;STDIN&gt;)
    {
        ...
    }</code>
</pre></div>
<p>Use <code>$_</code> as you would the word "it" in formal writing: sparingly, in small and well-defined scopes.</p>
<div class="tip">
<div id="ibuiltins__i464646_0"></div>
<p>Perl 5.12 introduced the triple-dot (<code>...</code>) operator as a placeholder for code you intend to fill in later. Perl will parse it as a complete statement, but will throw an exception that you're trying to run unimplemented code if you try to run it. See <code>perldoc perlop</code> for more details.</p>
</div>
<h3 id="heading_id_10">The Default Array Variables</h3>
<div id="default_array_variables"></div>
<div id="idefault_variables__iarray_0"></div>
<div id="idefault_variables__i64__0"></div>
<div id="ivariables__i64__0"></div>
<div id="i64__0"></div>
<p>Perl also provides two implicit array variables. Perl passes arguments to functions (<a href="chapter_05.html#functions">Declaring Functions</a>(functions)) in an array named <code>@_</code>. Array manipulation operations (<a href="chapter_03.html#arrays">Arrays</a>(arrays)) inside functions affect this array by default, so these two snippets of code are equivalent:</p>
<div class="programlisting">
<pre>
<code>    sub foo
    {
        my $arg = shift;
        ...
    }

    sub foo_explicit_args
    {
        my $arg = shift @_;
        ...
    }</code>
</pre></div>
<div id="ibuiltins__ishift_0"></div>
<div id="ibuiltins__ipop_0"></div>
<p>Just as <code>$_</code> corresponds to the pronoun <em>it</em>, <code>@_</code> corresponds to the pronouns <em>they</em> and <em>them</em>. <em>Unlike</em> <code>$_</code>, Perl automatically localizes <code>@_</code> for you when you call other functions. The builtins <code>shift</code> and <code>pop</code> operate on <code>@_</code> with no other operands provided.</p>
<div id="idefault_variables__i64ARGV_0"></div>
<div id="ivariables__i64ARGV_0"></div>
<div id="i64ARGV_0"></div>
<p>Outside of all functions, the default array variable <code>@ARGV</code> contains the command-line arguments to the program. Perl's array operations (including <code>shift</code> and <code>pop</code>) operate on <code>@ARGV</code> implicitly outside of functions. You cannot use <code>@_</code> when you mean <code>@ARGV</code>.</p>
<div class="tip">
<div id="ibuiltins__ireadline_0"></div>
<div id="ibuiltins__iglob_0"></div>
<p>Perl's <code>&lt;$fh&gt;</code> operator is the same as the <code>readline</code> builtin. <code>readline $fh</code> does the same thing as <code>&lt;$fh&gt;</code>. As of Perl 5.10, a bare <code>readline</code> behaves just like <code>&lt;&gt;</code>, so you can now use <code>readline</code> everywhere. For historic reasons, <code>&lt;&gt;</code> is still more common, but consider using <code>readline</code> as a more readable alternative. You probably prefer <code>glob '*.html'</code> to <code>&lt;*.html&gt;</code>, right? It's the same idea.</p>
</div>
<div id="inull_filehandle_0"></div>
<p><code>ARGV</code> has one special case. If you read from the null filehandle <code>&lt;&gt;</code>, Perl will treat every element in <code>@ARGV</code> as the <em>name</em> of a file to open for reading. (If <code>@ARGV</code> is empty, Perl will read from standard input.) This implicit <code>@ARGV</code> behavior is useful for writing short programs, such as this command-line filter which reverses its input:</p>
<div class="programlisting">
<pre>
<code>    while (&lt;&gt;)
    {
        chomp;
        say scalar reverse;
    }</code>
</pre></div>
<p>Why <code>scalar</code>? <code>say</code> imposes list context on its operands. <code>reverse</code> passes its context on to its operands, treating them as a list in list context and a concatenated string in scalar context. If the behavior of <code>reverse</code> sounds confusing, your instincts are correct. Perl 5 arguably should have separated "reverse a string" from "reverse a list".</p>
<p>If you run it with a list of files:</p>
<div class="screen">
<pre>
<code>    $ <strong>perl reverse_lines.pl encrypted/*.txt</strong></code>
</pre></div>
<p>... the result will be one long stream of output. Without any arguments, you can provide your own standard input by piping in from another program or typing directly. Yet Perl is good for far more than small command-line programs....</p>
</body>
</html>