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

📄 rhl29.htm

📁 linux的初学电子书
💻 HTM
📖 第 1 页 / 共 5 页
字号:

<BR>

<PRE>

<FONT COLOR="#000080">1 #!/usr/bin/perl

2 #

3 # An example to show how arrays work in Perl

4 #

5 @amounts = (10,24,39);

6 @parts = ('computer', 'rat', &quot;kbd&quot;);

7

8 $a = 1; $b = 2; $c = '3';

9 @count = ($a, $b, $c);

10

11 @empty = ();

12

13 @spare = @parts;

14

15 print '@amounts = ';

16 print &quot;@amounts \n&quot;;

17

18 print '@parts = ';

19 print &quot;@parts \n&quot;;

20

21 print '@count = ';

22 print &quot;@count \n&quot;;

23

24 print '@empty = ';

25 print &quot;@empty \n&quot;;

26

27 print '@spare = ';

28 print &quot;@spare \n&quot;;

29

30

31 #

32 # Accessing individual items in an array

33 #

34 print '$amounts[0] = ';

35 print &quot;$amounts[0] \n&quot;;

36 print '$amounts[1] = ';

37 print &quot;$amounts[1] \n&quot;;

38 print '$amounts[2] = ';

39 print &quot;$amounts[2] \n&quot;;

40 print '$amounts[3] = ';

41 print &quot;$amounts[3] \n&quot;;

42

43 print &quot;Items in \@amounts = $#amounts \n&quot;;

44 $size = @amounts; print &quot;Size of Amount = $size\n&quot;;

45 print &quot;Item 0 in \@amounts = $amounts[$[]\n&quot;;

46

@amounts = 10 24 39

@parts = computer rat kbd

@count = 1 2 3

@empty =

@spare = computer rat kbd

$amounts[0] = 10

$amounts[1] = 24

$amounts[2] = 39

$amounts[3] =

Items in @amounts = 2

Size of Amount = 3

Item 0 in @amounts = 10</FONT></PRE>

<P>In line 5, three integer values are assigned the @amounts array. In line 6, three strings are assigned to the @parts array. In line 8, the script assigns both string and numeric values to variables and then assigns the values of the variable to the 
@count array. An empty array is created in line 11. In line 13, the @spare array is assigned the same values as those in @parts.

<BR>

<P>Lines 15 through 28 print out the first five lines of the output. In lines 34 to 41, the script addresses individual items of the @amounts array. Note that $amount[3] does not exist; it is therefore printed as an empty item.

<BR>

<P>The $#array syntax is used in line 43 to print the last index in an array, so the script prints 2. The size of the amounts array would be ($#amounts + 1). If an array is assigned to a scalar, as shown in line 44, the size of the array is assigned to the 
scalar. Line 45 shows the use of a special Perl variable called $[, which is the base subscript (zero, unless you redefine it) of an array.

<BR>

<BR>

<A NAME="E69E363"></A>

<H4 ALIGN=CENTER>

<CENTER>

<FONT SIZE=4 COLOR="#FF0000"><B>Associative Arrays</B></FONT></CENTER></H4>

<BR>

<P>An associative array is really an array with two items per index. The first item at each index is called a key and the other item is called the value. You index into an associative array using keys to get values. An associative array name is preceded 
with a percent sign (%), and indexed items are with curly braces ({}).

<BR>

<P>See Listing 29.3 for some sample uses of associative arrays.

<BR>

<P>

<FONT COLOR="#000080"><B>Listing 29.3. Using associative arrays.</B></FONT>

<BR>

<PRE>

<FONT COLOR="#000080">1 #!/usr/bin/perl

2 #

3 # Associative Arrays.

4 #

5

6 %subscripts = (

7 'bmp', 'Bitmap',

8 &quot;cpp&quot;, &quot;C++ Source&quot;,

9 &quot;txt&quot;, 'Text file' );

10

11 $bm = 'asc';

12 $subscripts{$bm} = 'Ascii File';

13

14 print &quot;\n =========== Raw dump of hash ========= \n&quot;;

15 print %subscripts;

16

17 print &quot;\n =========== using foreach ========= \n&quot;;

18 foreach $key (keys (%subscripts)) {

19 $value = $subscripts{$key};

20 print &quot;Key = $key, Value = $value \n&quot;;

21 }

22

23 print &quot;\n === using foreach with sort ========= \n&quot;;

24 foreach $key (sort keys (%subscripts)) {

25 $value = $subscripts{$key};

26 print &quot;Key = $key, Value = $value \n&quot;;

27 }

28

29 print &quot;\n =========== using each() ========= \n&quot;;

30 while (($key,$value) = each(%subscripts)) {

31 print &quot;Key = $key, Value = $value \n&quot;;

32 }

33

=========== Raw dump of hash =========

txtText filecppC++ SourceascAscii FilebmpBitmap

=========== using foreach =========

Key = txt, Value = Text file

Key = cpp, Value = C++ Source

Key = asc, Value = Ascii File

Key = bmp, Value = Bitmap

=== using foreach with sort =========

Key = asc, Value = Ascii File

Key = bmp, Value = Bitmap

Key = cpp, Value = C++ Source

Key = txt, Value = Text file

=========== using each() =========

Key = txt, Value = Text file

Key = cpp, Value = C++ Source

Key = asc, Value = Ascii File

Key = bmp, Value = Bitmap</FONT></PRE>

<P>An associative array called %subscripts is created in line 6 up to line 9. Three items of (key,value) pairs are added to %subscripts as a list. At line 11, a new item is added to the %subscript array by assigning $bm to a key and then using $bm as the 
index. We could just as easily add the string 'Ascii File' with the hard-coded statement:

<BR>

<BR>

<PRE>

<FONT COLOR="#000080">$subscripts{'asc'} = 'Ascii File';</FONT></PRE>

<P>Look at the output from line 15 which dumps out the associative array items.

<BR>

<P>In line 17, the script uses a foreach statement to loop over the keys in the %subscripts array. The keys() function returns a list of keys for a given hash. The value of the item at $subscripts{$key} is assigned to $value at line 19. You could combine 
lines 18 and 19 into one statement like this without loss of meaning:

<BR>

<BR>

<PRE>

<FONT COLOR="#000080">print &quot;Key = $key, Value = $subscripts{$key} \n&quot;;</FONT></PRE>

<P>Using the keys alone did not list the contents of the %subscripts hash in the order you want. To sort the output, you should sort the keys into the hash. This is shown in line 24. The sort() function takes a list of items and returns a text-sorted 
version. The foreach function takes the output from the sort() function applied to the value returned by the keys() function. To sort in decreasing order, you can apply the reverse function to the returned value of sort() to get this line:

<BR>

<BR>

<PRE>

<FONT COLOR="#000080">foreach $key (reverse sort keys (%subscripts)) {</FONT></PRE>

<P>It's more efficient to use the each() function when working with associative arrays, because only one lookup is required per item to get both the key and its value. See line 30 where the ($key,$value) pairs assigned to the value are returned by the 
each() command.

<BR>

<P>The code in line 30 is important and deserves some explaining. First of all, the while() loop is used here. The format for a while loop is defined as:

<BR>

<PRE>

<FONT COLOR="#000080">while( conditionIsTrue) {

codeInLOOP

}

..

codeOutOfLOOP</FONT></PRE>

<P>While the condition in the while loop is a nonzero number, a nonempty string, or a nonempty list, the code in the area codeInLOOP will be executed. Otherwise, the next statement outside the loop (for instance, after the curly brace) will be executed.

<BR>

<P>Secondly, look at how the list ($key,$value) is mapped onto the list returned by the each function. The first item of the returned list is assigned to $key, the next item to $value. This is part of the array slicing operations available in Perl.

<BR>

<BR>

<A NAME="E68E232"></A>

<H3 ALIGN=CENTER>

<CENTER>

<FONT SIZE=5 COLOR="#FF0000"><B>Array Operations</B></FONT></CENTER></H3>

<BR>

<P>When working with arrays in Perl, you are really working with lists. You can add or remove items from the front or back of the list. Items in the middle of the list can be indexed using subscripts or keys. Sublists can be created from lists. Lists can 
be concatenated to create new lists. Got all that?

<BR>

<P>Let's look at some examples of how they fit together. See Listing 29.4, which uses some of these concepts.

<BR>

<P>

<FONT COLOR="#000080"><B>Listing 29.4. Array operations.</B></FONT>

<BR>

<PRE>

<FONT COLOR="#000080">1 #!/usr/bin/perl

2 #

3 # Array operations

4 #

5

6 $a = 'RFI';

7 $b = 'UPS';

8 $c = 'SPIKE';

9

10 @words = ('DC','AC','EMI','SURGE');

11

12 $count = @words; # Get the count

13

14 #

15 # Using the for operator on a list

16 #

17 print &quot;\n \@words = &quot;;

18 for $i (@words) {

19 print &quot;[$i] &quot;;

20 }

21

22 print &quot;\n&quot;;

23 #

24 # Using the for loop for indexing

25 #

26 for ($i=0;$i&lt;$count;$i++) {

27 print &quot;\n Words[$i] : $words[$i];&quot;;

28 }

29 #

30 # print 40 equal signs

31 #

32 print &quot;\n&quot;;

33 print &quot;=&quot; x 40;

34 print &quot;\n&quot;;

35 #

36 # Extracting items into scalars

37 #

38 ($x,$y) = @words;

39 print &quot;x = $x, y = $y \n&quot;;

40 ($w,$x,$y,$z) = @words;

41 print &quot;w = $x, x = $x, y = $y, z = $z\n&quot;;

42

43 ($anew[0], $anew[3], $anew[9], $anew[5]) = @words;

44

45 $temp = @anew;

46

47 #

48 # print 40 equal signs

49 #

50 print &quot;=&quot; x 40;

51 print &quot;\n&quot;;

52

53 print &quot;Number of elements in anew = &quot;. $temp, &quot;\n&quot;;

54 print &quot;Last index in anew = &quot;. $#anew, &quot;\n&quot;;

55 print &quot;The newly created Anew array is: &quot;;

56 $j = 0;

57 for $i (@anew) {

58 print &quot;\n \$anew[$j] = is $i &quot;;

59 $j++;

60 }

61 print &quot;\n&quot;;

62

63

@words = [DC] [AC] [EMI] [SURGE]

Words[0] : DC;

Words[1] : AC;

Words[2] : EMI;

Words[3] : SURGE;

========================================

x = DC, y = AC

w = AC, x = AC, y = EMI z = SURGE

========================================

Number of elements in anew = 10

Last index in anew = 9

The newly created Anew array is:

$anew[0] = is DC

$anew[1] = is

$anew[2] = is

$anew[3] = is AC

$anew[4] = is

$anew[5] = is SURGE

$anew[6] = is

$anew[7] = is

$anew[8] = is

$anew[9] = is EMI</FONT></PRE>

<P>Lines 6, 7, and 8 assign values to scalars $a, $b and $c. In line 10, four values are assigned to the @words array. Line 12 gives a count of the number of elements in the array.

<BR>

<P>The for loop statement is used to cycle through each element in the list. Perl takes each item in the @words array, assigns it to $i and then executes the statements in the block of code between the curly braces. We could rewrite line 18 as the 
following and get the same result:

<BR>

<BR>

<PRE>

<FONT COLOR="#000080">for $i ('DC','AC','EMI','SURGE') {</FONT></PRE>

<P>In the case of the sample in Listing 29.4, you print the value of each item with square brackets around them. Line 22 simply prints a new line.

<BR>

<P>Now look at line 26, where the for loop is defined. The syntax in the for() loop will be very familiar to C programmers:

<BR>

<PRE>

<FONT COLOR="#000080">for (startingCondition; endingCondition; at_end_of_every_loop) {

execute_statements_in_this_block;

}</FONT></PRE>

<P>Line 26 sets $i to zero when the for loop is started. Before Perl executes the next statement within the block, it checks to see if $i is less than $count. If $i is less than $count, the print statement is executed. If $i is greater than or equal to 
$count, the next statement following the ending curly brace will be executed. After executing the last statement in a for() loop code block, line 28, Perl increments the value of with the end of loop statement: $i++. So $i is incremented. Perl goes back to 
the top of the loop to test for the ending condition to see what to do next.

<BR>

<P>In the next lines 32 through 34, we print an output delimiting line with 40 equals signs. The x operator in line 33 will cause the = to be repeated by the number following it. Another way to print a somewhat fancier line would be to do the following in 
lines 32-34:

<BR>

<PRE>

<FONT COLOR="#000080">32 print &quot;\n[&quot;;

33 print &quot;-=&quot; x 20;

34 print &quot;]\n&quot;;</FONT></PRE>

<P>Next, line 38 takes the first two items in @words and assigns them to variables $x and $y, respectively. The rest of the items in @words are not used. Line 40 assigns four items from @words to four variables. The mapping of items from @words to 
variables is done on a one-to-one basis based on the type of parameter on the left-hand side of the = sign..

<BR>

<P>Had you used the following line in place of line 40, you would get the value of $word[0] in $x and the rest of @word in @sublist:

<BR>

<BR>

<PRE>

<FONT COLOR="#000080"> ($x,@sublist) = @words;</FONT></PRE>

<P>Line 43 creates a new array, @anew, and assigns it values from the @words array&#151;but not on a one-to-one basis. In fact, you will see that the @anew array is not even the same size as @words. Perl automatically resizes the @anew array to be at least 
as large as the largest index. In this case, since $anew[9] is being assigned a value, @anew will be at least 10 items long to cover items from 0 to 9.

<BR>

<P>In lines 53 and 54, the script prints out the value of the number of elements in the array and the highest valid index in the array. Lines 57 through 60 print out the value of each item in the anew area. Notice that items in the @new array are not 
assigned any values.

<BR>

⌨️ 快捷键说明

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