📄 rhl29.htm
字号:
<P>You can create other lists from lists as well. See the example in Listing 29.5.
<BR>
<P>
<FONT COLOR="#000080"><B>Listing 29.5. Creating sublists.</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 # Using the for operator on a list
15 #
16 print "\n \@words = ";
17 for $i (@words) {
18 print "[$i] ";
19 }
20
21 print "\n";
22 print "=" x 40;
23 print "\n";
24
25 #
26 # Concatenate lists together
27 #
28 @more = ($c,@words,$a,$b);
29 print "\n Putting a list together: ";
30 $j = 0;
31 for $i (@more) {
32 print "\n \$more[$j] = is $i ";
33 $j++;
34 }
35 print "\n";
36
37 @more = (@words,($a,$b,$c));
38 $j = 0;
39 for $i (@more) {
40 print "\n \$more[$j] = is $i ";
41 $j++;
42 }
43 print "\n";
44
45
46 $fourth = ($a x 4);
47 print " is $fourth\n";
@words = [DC] [AC] [EMI] [SURGE]
========================================
Putting a list together:
$more[0] = is SPIKE
$more[1] = is DC
$more[2] = is AC
$more[3] = is EMI
$more[4] = is SURGE
$more[5] = is RFI
$more[6] = is UPS
$more[0] = is DC
$more[1] = is AC
$more[2] = is EMI
$more[3] = is SURGE
$more[4] = is RFI
$more[5] = is UPS
$more[6] = is SPIKE
$more[0] = is RFIRFIRFIRFI</FONT></PRE>
<P>Listing 29.5 creates one list from another list. In line 10, the script creates and fills the @words array. In lines 16 through 19, the script prints out the array. Lines 21-23, which print equal signs to create a divider, are repeated again (which you
will soon convert into a subroutine).
<BR>
<P>At line 28, the @more array is created by placing $c, the entire @words array, $a, and $b together. The size of the @more array will be 6. The items in the @more array are printed out in lines 31 through 35.
<BR>
<P>The code at line 37 creates another @more array with different ordering. The previously created @more array is freed back to the memory pool. The newly ordered @more list is printed from lines 38 through 43.
<BR>
<P>The script then uses the x operator in line 46 to create another item by concatenating four copies of $a into the variable $fourth.
<BR>
<P>If you are like me, you probably don't want to type the same lines of code again and again. For example, the code in lines 21-23 of Listing 29.5 could be made into a function that looks like this:
<BR>
<PRE>
<FONT COLOR="#000080">sub printLine {
print "\n";
print "=" x 40;
print "\n";
}</FONT></PRE>
<P>Now when you want to print the lines, call the subroutine with this line of code:
<BR>
<BR>
<PRE>
<FONT COLOR="#000080">&printLine;</FONT></PRE>
<P>The section "Subroutines" covers other aspects of subroutines. For now, let's get back to some of the things you can do with arrays using the functions supplied with Perl. See Listing 29.6 for a script that uses the array functions discussed
here.
<BR>
<P>
<FONT COLOR="#000080"><B>Listing 29.6. Using array functions.</B></FONT>
<BR>
<PRE>
<FONT COLOR="#000080">1 #!/usr/bin/perl
2 #
3 # Functions for Arrays
4 #
5 sub printLine {
6 print "\n"; print "=" x 60; print "\n";
7 }
8
9 $quote= 'Listen to me slowly';
10
11 #
12 # USING THE SPLIT function
13 #
14 @words = split(' ',$quote);
15
16 #
17 # Using the for operator on a list
18 #
19 &printLine;
20 print "The quote from Sam Goldwyn: $quote ";
21 &printLine;
22 print "The words \@words = ";
23 for $i (@words) {
24 print "[$i] ";
25 }
26
27 #
28 # CHOP
29 #
30 &printLine;
31 chop(@words);
32 print "The chopped words \@words = ";
33 for $i (@words) {
34 print "[$i] ";
35 }
36 print "\n .. restore";
37 #
38 # Restore!
39 #
40 @words = split(' ',$quote);
41
42 #
43 # Using PUSH
44 #
45 @temp = push(@words,"please");
46 &printLine;
47 print "After pushing \@words = ";
48 for $i (@words) {
49 print "[$i] ";
50 }
51
52 #
53 # USING POP
54 #
55 $temp = pop(@words); # Take the 'please' off
56 $temp = pop(@words); # Take the 'slowly' off
57 &printLine;
58 print "Popping twice \@words = ";
59 for $i (@words) {
60 print "[$i] ";
61 }
62 #
63 # SHIFT from the from the top of the array.
64 #
65 $temp = shift @words;
66 &printLine;
67 print "Shift $temp off, \@words= ";
68 for $i (@words) {
69 print "[$i] ";
70 }
71 #
72 # Restore words
73 #
74 @words = ();
75 @words = split(' ',$quote);
76 &printLine;
77 print "Restore words";
78 #
79 # SPLICE FUNCTION
80 #
81 @two = splice(@words,1,2);
82 print "\n Words after splice = ";
83 for $i (@words) {
84 print " [$i]";
85 }
86 print "\n Returned from splice = ";
87 for $i (@two) {
88 print " [$i]";
89 }
90 &printLine;
91
92 #
93 # Using the join function
94 #
95 $joined = join(":",@words,@two);
96 print "\n Returned from join = $joined ";
97 &printLine;</FONT></PRE>
<P>The split function is used in line 14 to split the items in the string $quote into the @words array.
<BR>
<P>Then the script uses chop() on a list. This function removes a character from a string. When applied to an array, chop removes a character from each item on the list. See lines 31 through 35.
<BR>
<P>You can add or delete items from an array using the pop(@Array) or push(@Array) functions. The pop() function removes the last item from a list and returns it as a scalar. In the push(ARRAY,LIST);, the push() function takes an array as the first
parameter and treats the rest of the parameters as items to place at the end of the array. In line 45, the push function pushes the word please into the back of the @words array. In lines 55 and 56, two words are popped off the @words list. The size of the
array @word changes with each command.
<BR>
<P>Let's look at how the shift function in used in line 65. The shift(ARRAY) function returns the first element of an array. The size of the array is decreased by 1. You can use shift in one of three ways listed here:
<BR>
<PRE>
<FONT COLOR="#000080">shift (@mine); # return first item of @mine
shift @mine; # return first item of @mine
shift; # return first item in @ARGV</FONT></PRE>
<P>The special variable @ARGV is the argument vector for your Perl program.
<BR>
<BLOCKQUOTE>
<BLOCKQUOTE>
<HR ALIGN=CENTER>
<BR>
<NOTE>The push/pop routines work on the back of an array and the shift/unshift routines work on the front of an array.</NOTE>
<BR>
<HR ALIGN=CENTER>
</BLOCKQUOTE></BLOCKQUOTE>
<P>The number of elements in @ARGV are easily found by assigning a scalar to $ARGC, which is equal to @#ARGV before any operations are applied to @ARGV.
<BR>
<P>Then, after restoring @words to its original value, the script uses the splice( ) function to remove items from the @words array. The splice function is very important function and is really the key behind the pop(), push(), and shift() functions. The
syntax for the splice() function is:
<BR>
<BR>
<PRE>
<FONT COLOR="#000080">splice(@array,$offset,$length,$list)</FONT></PRE>
<P>The splice function will return the items removed in the form of a list. It will replace the $length items in @array starting from $offset with the contents of $list. If you leave out the $list parameter, and just use splice(@array,$offset,$length),
then nothing will be inserted in the original array. Any removed items will be returned from splice().If you leave out the $length paramater to splice and use it as splice(@array,$offset), then $length will be set the length of the @array from the offset.
<BR>
<BR>
<A NAME="E68E233"></A>
<H3 ALIGN=CENTER>
<CENTER>
<FONT SIZE=5 COLOR="#FF0000"><B>File Handles and Operators</B></FONT></CENTER></H3>
<BR>
<P>Now that we have covered basic array and numeric operations, let's cover some of the input/output operations where files are concerned. A Perl program has three file handles when it starts up: STDIN (for standard input), STDOUT (for standard output) and
STDERR (for standard error message output). Note the use of capitals and the lack of the $ sign to signify that these are file handles. For a C/C++ programmer, the three handles would be akin to stdin, stdout and stderr.
<BR>
<P>To open a file for I/O you have to use the open statement. The syntax for the open call is:
<BR>
<BR>
<PRE>
<FONT COLOR="#000080">open(HANDLE, $filename);</FONT></PRE>
<P>The HANDLE is then used for all the operations on a file. To close a file, you would use the function close HANDLE;
<BR>
<P>For writing text to a file given a handle, you can use the print statements to write to the file:
<BR>
<BR>
<PRE>
<FONT COLOR="#000080">print HANDLE $output;</FONT></PRE>
<P>The HANDLE defaults to STDIN if no handle is specified. To read one line from the file given a HANDLE you will use the <> operators:
<BR>
<BR>
<PRE>
<FONT COLOR="#000080">$line = <HANDLE></FONT></PRE>
<P>In the preceding code, $line will be assigned all the input until a carriage return or eof. When writing interactive scripts, you normally use the chop() function to remove the end-of-line character. To read from the standard input into a variable
$response, you would use the statements in sequence:
<BR>
<PRE>
<FONT COLOR="#000080">$response = <STDIN>;
chop $response; # remove offensive carriage return.</FONT></PRE>
<P>You can do binary read and write operations on a file using the read() and write functions. The syntax for each type of function is:
<BR>
<BR>
<PRE>
<FONT COLOR="#000080">read(HANDLE,$buffer,$length[,$offset]);</FONT></PRE>
<P>The read function will read from HANDLE into $buffer, up $length bytes from the $offset in bytes from the start of the file. The $offset is optional and read() defaults reading to the current location in the file if $offset is left out. The location in
the file to read from is advanced $length bytes. To check if you have reached the end of file, use the command:
<BR>
<BR>
<PRE>
<FONT COLOR="#000080">eof(HANDLE);</FONT></PRE>
<P>A nonzero value returned will signify the end of the file, and a zero returned will indicate that there is more to read in the file. You can move to a position in the file using the seek function.
<BR>
<BR>
<PRE>
<FONT COLOR="#000080">seek(HANDLE,$offset,$base)</FONT></PRE>
<P>The $offset is from the location specified in $base. The seek function behaves exactly like the C function call. If $base is 0, the $Offset is from the start of the file.
<BR>
<P>There can be errors associated with opening files, so to print out error messages before a script crashes the die() function is used. A call to open a file called "test.data" would look like this:
<BR>
<BR>
<PRE>
<FONT COLOR="#000080">open(TESTFILE,"test.data") || die "\n $0 Cannot open $! \n";</FONT></PRE>
<P>The preceding line literally reads, "Open test.data for input or die if you cannot open it". The $0 is the Perl special variable for the process name and $! is the errno from the system as a string.
<BR>
<P>The filename signifies the type of operation you intend to perform with the file. Table 29.4 lists some of the ways you can open a file.
<BR>
<BR>
<P ALIGN=CENTER>
<CENTER>
<FONT COLOR="#000080"><B>Table 29.4. File open types.</B></FONT></CENTER>
<BR>
<TABLE BORDERCOLOR=#000040 BORDER=1 CELLSPACING=2 WIDTH="100%" CELLPADDING=2 >
<TR>
<TD VALIGN=top BGCOLOR=#80FFFF ><FONT COLOR=#000080>
<I>File </I>
</FONT>
<TD VALIGN=top BGCOLOR=#80FFFF ><FONT COLOR=#000080>
<I>Action</I></FONT>
<TR>
<TD VALIGN=top BGCOLOR=#80FFFF ><FONT COLOR=#000080>
"test.data"
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -