⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ch5.htm

📁 this is a book on pearl , simple example with explanation is given here. it could be beneficial for
💻 HTM
📖 第 1 页 / 共 4 页
字号:
perform iNClude deleting elements, checking for the existeNCeof an element, reversing all of the the elements in an array,and sorting the elements. Table 5.2 lists the fuNCtions you canuse with arrays.<BR><P><CENTER><B>Table 5.2&nbsp;&nbsp;Array FuNCtions</B></CENTER><p><CENTER><TABLE BORDERCOLOR=#000000 BORDER=1 WIDTH=80%><TR><TD WIDTH=205><I>FuNCtion</I></TD><TD WIDTH=385><I>Description</I></TD></TR><TR><TD WIDTH=205><TT>defined(VARIABLE)</TT></TD><TD WIDTH=385>Returns true if <TT>VARIABLE</TT> has a real value and if the variable has not yet been assigned a value. This is not limited to arrays; any data type can be checked. Also see the <TT>exists</TT> fuNCtion for information about associative array keys.</TD></TR><TR><TD WIDTH=205><TT>delete(KEY)</TT></TD><TD WIDTH=385>Removes the key-value pair from the given associative array. If you delete a value from the <TT>%ENV</TT> array, the environment of the current process is changed, not that of the parent.</TD></TR><TR><TD WIDTH=205><TT>each(ASSOC_ARRAY)</TT></TD><TD WIDTH=385>Returns a two-element list that contains a key and value pair from the given associative array. The fuNCtion is mainly used so  you can iterate over the associate array elements. A null list is returned when the last element has been read.</TD></TR><TR><TD WIDTH=205><TT>exists(KEY)</TT></TD><TD WIDTH=385>Returns true if the <TT>KEY</TT> is part of the specified associative array. For instaNCe, <TT>exists($array{&quot;Orange&quot;})</TT> returns true if the <TT>%array</TT> associative array has a key with the value of &quot;Orange.&quot;</TD></TR><TR><TD WIDTH=205><TT>join(STRING, ARRAY)</TT></TD><TD WIDTH=385>Returns a string that consists of all of the elements of <TT>ARRAY</TT> joined together by <TT>STRING</TT>. For instaNCe, <TT>join(&quot;&gt;&gt;&quot;, (&quot;AA&quot;, &quot;BB&quot;, &quot;cc&quot;))</TT> returns <TT>&quot;AA&gt;&gt;BB&gt;&gt;cc&quot;</TT>.</TD></TR><TR><TD WIDTH=205><TT>keys(ASSOC_ARRAY)</TT></TD><TD WIDTH=385>Returns a list that holds all of the keys in a given associative array. The list is not in any particular order.</TD></TR><TR><TD WIDTH=205><TT>map(EXPRESSION, ARRAY)</TT></TD><TD WIDTH=385>Evaluates <TT>EXPRESSION</TT> for every element of <TT>ARRAY</TT>. The special variable <TT>$ </TT>is assigned each element of <TT>ARRAY</TT> immediately before <TT>EXPRESSION</TT> is evaluated.</TD></TR><TR><TD WIDTH=205><TT>pack(STRING, ARRAY)</TT></TD><TD WIDTH=385>Creates a binary structure, using <TT>STRING</TT> as a guide, of the elements of <TT>ARRAY</TT>. You can look in <A HREF="ch8.htm" >Chapter 8</A> &quot;RefereNCes,&quot; for more information.</TD></TR><TR><TD WIDTH=205><TT>pop(ARRAY)</TT></TD><TD WIDTH=385>Returns the last value of an array. It also reduces the size of the array by one.</TD></TR><TR><TD WIDTH=205><TT>push(ARRAY1, ARRAY2)</TT></TD><TD WIDTH=385>Appends the contents of <TT>ARRAY2</TT> to <TT>ARRAY1</TT>. This iNCreases the size of <TT>ARRAY1</TT> as needed.</TD></TR><TR><TD WIDTH=205><TT>reverse(ARRAY)</TT></TD><TD WIDTH=385>Reverses the elements of a given array when used in an array context. When used in a scalar context, the array is converted to a string, and the string is reversed.</TD></TR><TR><TD WIDTH=205><TT>scalar(ARRAY)</TT></TD><TD WIDTH=385>Evaluates the array in a scalar context and returns the number of elements in the array.</TD></TR><TR><TD WIDTH=205><TT>shift(ARRAY)</TT></TD><TD WIDTH=385>Returns the first value of an array. It also reduces the size of the array by one.</TD></TR><TR><TD WIDTH=205><TT>sort(ARRAY)</TT></TD><TD WIDTH=385>Returns a list containing the elements of <TT>ARRAY</TT> in sorted order. See <A HREF="ch8.htm" >Chapter 8</A> &quot;RefereNCes,&quot; for more information.</TD></TR><TR><TD WIDTH=205><TT>splice(ARRAY1, OFFSET, </TT></TD><TD WIDTH=385>Replaces elements of <TT>ARRAY1</TT> with elements </TD></TR><TR><TD WIDTH=205><TT>LENGTH, ARRAY2)</TT></TD><TD WIDTH=385>in <TT>ARRAY2</TT>. It returns a list holding any elements that were removed. Remember that the <TT>$[</TT> variable may change the base array subscript when determining the <TT>OFFSET</TT> value.</TD></TR><TR><TD WIDTH=205><TT>split(PATTERN, STRING, LIMIT)</TT></TD><TD WIDTH=385>Breaks up a string based on some delimiter. In an array context, it returns a list of the things that were found. In a scalar context, it returns the number of things found.</TD></TR><TR><TD WIDTH=205><TT>undef(VARIABLE)</TT></TD><TD WIDTH=385>Always returns the undefined value. In addition, it undefines <TT>VARIABLE</TT>, which must be a scalar, an entire array, or a subroutine name.</TD></TR><TR><TD WIDTH=205><TT>unpack(STRING, ARRAY)</TT></TD><TD WIDTH=385>Does the opposite of <TT>pack()</TT>. </TD></TR><TR><TD WIDTH=205><TT>unshift(ARRAY1, ARRAY2)</TT></TD><TD WIDTH=385>Adds the elements of <TT>ARRAY2</TT> to the front of <TT>ARRAY1</TT>. Note that the added elements retain their original order. The size of the new <TT>ARRAY1</TT> is returned.</TD></TR><TR><TD WIDTH=205><TT>values(ASSOC_ARRAY)</TT></TD><TD WIDTH=385>Returns a list that holds all of the values in a given associative array. The list is not in any particular order.</TD></TR></TABLE></CENTER><P><P>As with the string fuNCtions, only a few of these fuNCtions willbe explored. ONCe you see the examples, you'll be able to handlethe rest with no trouble.<H3><A NAME="ExamplePrintinganAssociativeArray">Example: Printing an Associative Array</A></H3><P>The <TT>each()</TT> fuNCtion returnskey, value pairs of an associative array one-by-one in a list.This is called <I>iterating</I> over the elements of the array.Iteration is a synonym for looping. So, you also could say thatthe <TT>each()</TT> fuNCtion startsat the beginning of an array and loops through each element untilthe end of the array is reached. This ability lets you work withkey, value pairs in a quick easy manner.<P>The <TT>each()</TT> fuNCtion doesnot loop by itself. It needs a little help from some Perl controlstatements. For this example, we'll use the <I>while</I> loopto print an associative array. The <TT>while(CONDITION) {}</TT> control statement continues to executeany program code surrounded by the curly braces until the <TT>CONDITION</TT>turns false.<P><IMG SRC="pseudo.gif" BORDER=1 ALIGN=RIGHT><p><BLOCKQUOTE><I>Create an associative with number, color pairs.<BR>Using a while loop, iterate over the array elements.<BR>Print the key, value pair.</I></BLOCKQUOTE><BLOCKQUOTE><PRE>%array = ( &quot;100&quot;, &quot;Green&quot;, &quot;200&quot;, &quot;Orange&quot;);while (($key, $value) = each(%array)) {      print(&quot;$key = $value\n&quot;);}</PRE></BLOCKQUOTE><P>This program prints:<BLOCKQUOTE><PRE>100 = Green200 = Orange</PRE></BLOCKQUOTE><P>The <TT>each()</TT> fuNCtion returnsfalse when the end of the array is reached. Therefore, you canuse it as the basis of the <TT>while</TT>'scondition. When the end of the array is reached, the program continuesexecution after the closing curly brace. In this example, theprogram simply ends.<H3><A NAME="ExampleCheckingtheExisteNCeofanElement">Example: Checking the ExisteNCe of an Element</A></H3><P>You can use the <TT>defined()</TT>fuNCtion to check if an array element exists before you assigna value to it. This ability is very handy if you are reading valuesfrom a disk file and don't want to overlay values already in memory.For instaNCe, suppose you have a disk file of customers' addressesand you would like to know if any of them are duplicates. Youcheck for duplicates by reading the information one address ata time and assigning the address to an associative array usingthe customer name as the key value. If the customer name alreadyexists as a key value, then that address should be flagged forfollow up.<P>Because we haven't talked about disk files yet, we'll need toemulate a disk file with an associative array. And, instead ofusing customer's address, we'll use customer number and customername pairs. First, we see what happens when an associative arrayis created and two values have the same keys.<P><IMG SRC="pseudo.gif" BORDER=1 ALIGN=RIGHT><p><BLOCKQUOTE><I>Call the </I><TT><I>createPair()</I></TT><I>fuNCtion three times to create three key, value pairs in the </I><TT><I>%array</I></TT><I>associative array.<BR>Loop through </I><TT><I>%array</I></TT><I>,printing each key, value pair.<BR>Define the </I><TT><I>createPair()</I></TT><I>fuNCtion.<BR>Create local variables to hold the key, value pair passed as parameters.<BR>Create an array element to hold the key, value pair.</I></BLOCKQUOTE><BLOCKQUOTE><PRE>createPair(&quot;100&quot;,  &quot;Kathy Jones&quot;);createPair(&quot;200&quot;,  &quot;Grace Kelly&quot;);createPair(&quot;100&quot;, &quot;George Orwell&quot;);while (($key, $value) = each %array) {    print(&quot;$key, $value\n&quot;);};sub createPair{    my($key, $value) = @_ ;    $array{$key} = $value;};</PRE></BLOCKQUOTE><P>This program prints:<BLOCKQUOTE><PRE>100, George Orwell200, Grace Kelly</PRE></BLOCKQUOTE><P>This example takes advantages of the global nature of variables.Even though the <TT>%array</TT> elementis set in the <TT>createPair()</TT>fuNCtion, the array is still accessible by the main program. Noticethat the first key, value pair (100 and Kathy Jones) are overwrittenwhen the third key, value pair is eNCountered. You can see thatit is a good idea to be able to determine when an associativearray element is already defined so that duplicate entries canbe handled. The next program does this.<P><IMG SRC="pseudo.gif" BORDER=1 ALIGN=RIGHT><p><BLOCKQUOTE><I>Call the </I><TT><I>createPair()</I></TT><I>fuNCtion three times to create three key,  value pairs in the</I><TT><I>%array</I></TT><I> associativearray.<BR>Loop through </I><TT><I>%array</I></TT><I>,printing each key, value pair.<BR>Define the </I><TT><I>createPair()</I></TT><I>fuNCtion.<BR>Create local variables to hold the key, value pair passed as parameters.<BR>If the key, value pair already exists in </I><TT><I>%array</I></TT><I>,then iNCrement<BR> the customer number by one. Check to see if the new key, value<BR>pair exists. If so, keep iNCrementing until a nonexistent<BR>key, value pair is found.<BR>Create an array element to hold the key, value pair.</I></BLOCKQUOTE><BLOCKQUOTE><PRE>createPair(&quot;100&quot;,  &quot;Kathy Jones&quot;);createPair(&quot;200&quot;,  &quot;Grace Kelly&quot;);createPair(&quot;100&quot;, &quot;George Orwell&quot;);while (($key, $value) = each %array) {    print(&quot;$key, $value\n&quot;);};sub createPair{    my($key, $value) = @_ ;    while (defined($array{$key})) {        $key++;    }    $array{$key} = $value;};</PRE></BLOCKQUOTE><P>This program prints:<BLOCKQUOTE><PRE>100, George Orwell101, Kathy Jones200, Grace Kelly</PRE></BLOCKQUOTE><P>You can see that the customer number for Kathy Jones has beenchanged to 101. If the array had already had an entry for 101,the Kathy Jones' new customer number would be 102.<H2><A NAME="Summary"><FONT SIZE=5 COLOR=#FF0000>Summary</FONT></A></H2><P>In this chapter you've learned about fuNCtions-what they are andhow to call them. You saw that you can create your own fuNCtionor use one of Perl's many built-in fuNCtions. Each fuNCtion canaccept any number of parameters which get delivered to the fuNCtionin the form of the <TT>@ </TT>array.This array, like any other array in Perl, can be accessed usingthe array element to access an individual element. ( For instaNCe,<TT>$_ [0]</TT> accesses the firstelement in the <TT>@ </TT>array.)Because Perl parameters are passed by refereNCe, changing the<TT>@</TT> array changes the valuesin the main program as well as the fuNCtion.<P>You learned about the scope of variables and how all variablesare global by default. Then, you saw how to create variable withlocal scope using <TT>local()</TT>and <TT>my()</TT>. <TT>My()</TT>is the better choice in almost all situations because it enforceslocal scope and limits side effects from fuNCtion to inside thefuNCtions.<P>Then you saw that it was possible to nest fuNCtion calls, whichmeans that one fuNCtion can call another, which in turn can callanother. You  also might call this a chain of fuNCtion calls.Private fuNCtions were introduced next. A private fuNCtion isone that only can be used inside the fuNCtion that defines it.<P>A list of string fuNCtions then was presented. These iNCludedfuNCtions to remove the last character, eNCrypt a string, finda sub-string, convert array elements into a string, change thecase of a string character, and find the length of a string. Exampleswere shown about how to change a string's characters and how tosearch a string.<P>The section on array fuNCtions showed that Perl has a large numberof fuNCtions that deal specifically with arrays. The list of fuNCtionsiNCluded the ability to delete elements, return key, value pairsfrom associative arrays, reverse an array's elements, and sortan array. Examples were shown for printing an associative arrayand checking for the existeNCe of an element.<P>The next chapter, &quot;Statements,&quot; goes into detail aboutwhat statements are and how you create them. The information thatyou learned about variables and fuNCtions will come into play.You'll see how to link variables and fuNCtions together to formexpressions and statements.<H2><A NAME="ReviewQuestions"><FONT SIZE=5 COLOR=#FF0000>Review Questions</FONT></A></H2><P>Answers to Review Questions are in Appendix A.<OL><LI>What is a parameter?<LI>What two fuNCtions are used to create variables with localscope?<LI>What does parameter passing by refereNCe mean?<LI>What is the <TT>@_ </TT>arrayused for?<LI>Do Perl variables have global or local scope by default?<LI>Why is it hard to pass two arrays to a fuNCtion?<LI>What is the differeNCe between variables created with <TT>local()</TT>and variables created with <TT>my()</TT>?<LI>What does the <TT>map()</TT> fuNCtiondo?</OL><H2><A NAME="ReviewExercises"><FONT SIZE=5 COLOR=#FF0000>Review Exercises</FONT></A></H2><OL><LI>Create a fuNCtion that prints its own parameter list.<LI>Create a program that uses three fuNCtions to demonstratefuNCtion call nesting.<LI>Use the <TT>chop()</TT> fuNCtionin a program. Print both the returned character and the stringthat was passed as a parameter.<LI>Run the following program to see how many levels of recursionyour system configuration supports:<BR><BR><TT>firstSub();<BR><BR>sub firstSub{<BR>  print(&quot;$count\n&quot;);<BR>        $count++;<BR>        firstSub();<BR>}</TT><LI>Write a fuNCtion that uses the <TT>substr()</TT>and <TT>uc()</TT> fuNCtions to changethe tenth through twentieth characters to uppercase.<LI>Write a fuNCtion that uses the <TT>keys()</TT>fuNCtion to print out the values of an associative array.<LI>Create a program that uses a private fuNCtion to subtracttwo numbers and multiply the result by four.<LI>Write a program that shows what the <TT>shift()</TT>and <TT>unshift()</TT> fuNCtions do.<LI>Write a program that shows what the <TT>push()</TT>and <TT>pop()</TT> fuNCtions do.</OL><HR><CENTER><P><A HREF="ch4.htm"><IMG SRC="pc.gif" BORDER=0 HEIGHT=88 WIDTH=140></A><A HREF="#CONTENTS"><IMG SRC="cc.gif" BORDER=0 HEIGHT=88 WIDTH=140></A><A HREF="index.htm"><IMG SRC="hb.gif" BORDER=0 HEIGHT=88 WIDTH=140></A><A HREF="ch6.htm"><IMG SRC="nc.gif" BORDER=0 HEIGHT=88 WIDTH=140></A><HR WIDTH="100%"></P></CENTER></BODY></HTML>

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -