You are on page 1of 384

SAMS

24

Clinton

Pierce

SAMS

T e a c h

Y o u r s e l f

in 24 Hours

SAMS Macmillan
on,t,
?'?%?
2lSt.,Indianapolis,
Computer
201
West
103rd
I
Dh

SAMS

""
-*
2001

32.973.26-018.275
19
681.3.07

""
""
: info@williamspublishing.com, http://w\vw.\vi 11 iamspublishing.com

, .
19

Perl 24 . : . . : . . . : "", 2001. 384 .: . . . .


ISBN 5-8459-0097-2 (.)
Perl. ,
- . /
, . Perl CGl-.
.
32.973.26-018.2 75

.

, , , Sams
Publishing.
Authorized translation from the English language edition published by Sams Publishing Copyright 2000
All rights reserved. No part of this book may be reproduced or transmitted in any form or by any means,
electronic or mechanical, including photocopying, recording or by any information storage retrieval system, without
permission from the Publisher.
Russian language edition published by Williams Publishing House according to the Agreement with R&I
Enterprises International, Copyright 2000

ISBN 5-8459-0097-2 (.)


ISBN 0-672-31773-7 (.)

"", 2001
Sams Publishing, 1999

17

I. PERL

19

1 - . Perl
2- . Perl:
3- .
4- . :
5- .
6- .
7- .
8- .

II. PERL
9- .
10- .
11- .
12- . Perl
13- .
14- .
15- . Perl
16- . Perl

III. CGI- PERL


17- . CGI
18- .
19- .
20- . HTML- CGI-
21- . cookie
22- . CGI-
23- . Push- Web-
24- . Web-
. Perl

20
33
48
65
82
95
110
124

139
140
154
172
187
200
216
230
249

263
264
278
291
302
318
332
345
357
372
379
5

17

I. PERL

19

1- . Perl

20

Perl
Perl ?
Per! Windows 95/98/NT
Perl UNIX
Perl Macintosh


?



! ?
Perl

2- . Perl:




S_










:

21
21
23
23
25
25
26
26
27
28
28
29
29
29
30
30
31
31
32
32

33
34
34
34
36
37
38
38
39
39
40
41
41
. 42
43
43
44
46
46

46
46
47
47

3- .

48

49

if

Perl

49
51
53
54

56

while
for

if

Perl

57
57
58
58
59
60
60
61
62
63
63
63
64
64

4- . :

65

66
67
68
69
70
71
73
73
74
76
77
80
80
80
80
81
81

5- .


,


,

82

82
84
85
86
86
89
90

6- .

:




: grep

7- .











: Perl

91
9!
92
93
93
94
94
94
94

95
96
97
97
97
98
98
99
101
102
102
103
104
104
105
106
106
107
107
108
108
108
109

110
111
112
113
114
114
115
115
115
] 16
117
118
118
121
121
122
122
123
123

8- .

124




:

local
Perl

124
125
126
127
128
130
131
133
133
134
135
136
136
137
137
138

138

II. PERL

139

9- .

index

substr
,

:

10- .


: U N I X grep





U N I X


:

140
rindex

140
HI
142
143
143
144
146
149
151
151
151
152
152
153
153

154
155
156
158
160
160
161
162
163
163
164
165
168
169
169

11- .
system()





?

170
170
] 71
171

172
173
174
175
176
177
179
1S1
184
184
185
185
186
186

12- . Perl

187

Perl




:



187
188
189
190
I91
193
194
194
195
197
198
198
199
199
199

13- .





,

,
:

10

200
201
203
203
204

205
207
207
209
209
210
214
214
215
215
215
215

14- .


?



! -?
. , -!


15- . Perl
DBM

DBM-
:






UNIX Windows NT

Windows 9x
UNIX Windows NT

16- . Perl

216
217
218
219
220
220
222
223
224
224
225
227
227
228
228
228
229
229

230
230
232
232
233
236
238
239
239
240
241
242
245
246
246
247
247
248
248
248
248

249

Perl?

249

Perl

Perl
Perl (CPAN)
?
Perl?




-,

249
250
252
252
252
254
254
255
255
256
256
257

11

258
259
260
260
261
261

'

261

III. CGl- PERL

263

17- . CGI
Web
Web-
CG1 Web-


C G 1-
CGI-
CGI-
, CGI-
, ?

Internal Server Error 500 Error

18- .

'

265
265
266
267
268
269
270
271
272
272
273
274
275
275
276
276
276
277

278

278

HTML
Submit?
CGI-
GET POST
Web




278
280
281
282
283
283
284
285
286
286
288
289
289
289
290
290

19- .
Web- " "


12

264

291
291
292
292
293


'

'

20- . HTML- CGI-


HTTP
:
:
CGI-
CGI-

Web-
: SSI

299
300
300
300
301
301

302
302
304
304
307
307
308
309
311
313
314
316
316
316
316
317
317

21- . cookie

318

cookie

318

cookie
: cookie
: cookie
cookie
cookie

cookie
cookie
cookie
cookie
cookie
cookie
cookie

319
321
322
323
323
324
325
326
327
328
328
328
328
329
330
331
331
331
331

22- . CGI-
Internet



UNIX
UNIX
Web-

332
332
333
334
335
336
337
339

13

34!
342
342
343
343
343
344

23- . Push- Web-


push-

: &
:


, ,

24- . Web-

:
: ""
?
I:
II:

. Perl

...
...Windows 95/98/NT
...UNIX, CPAN
...UNIX,
Macintosh
,
,

14

345
345
346
347
348
349
350
352
353
355
355
355
355
356
356

357
357
358
359
362
364
366
369
369
370
370
370
370

372
372
373
373
374
376
377
377
378

379


, ""
. Perl, "Usenet, Perl
, , . ,
UNIX, CGI- Ford Motor,
UNIX Decision Consultants , ,
. Web http://www.geeksalad.org.

, " "
.
.

, .

, Perl. 1 .
, , . ,
, , . ,
. ,
,
. . , (Greg
Bacon), (Sean Bukre), (Ken Fox), (Kevin Meltzer),
(Tom Phoenix), (Michael Schwern),
(Grydeland), (Matt Bielanski), - (Mark JasonDominus), (Jeff Pinyan), (Gary Ross), (Andrew
Chen) (John Bell).
iperl ,
, .

' (Larry Wall) Per!. . .

15

(Bill Crawford)
(Donna Hinkle), -
. , .
, , Macmillan, ,

-. , (Randi Roger),
(Scott Meyers), (Chuck Hutchinson) ,
, .


, , . , ,
.
, .
. Web-, ,
, ,
, , .
, ,
e-mail.
. :
E-mail:
info@williamspublishing.com
WWW:

http://www.

williamspublishing.com

, , . , Web-. WWW

16


.
.
,
.
, , , , . ,
- , Perl. .
Web-,
Perl, -
.
,
Perl?
Perl. , - . , Perl. . .
, , Perl? ,
, - .
Perl , , , ,
. , ,
Internet World Wide Web Perl? , Perl ,
, , .
Perl , .
, .


24 , . .
( )
, 10 ,
. . .

,
Perl 24 .

17

. , ,
.
.
^

| Perl .

, .

18

I
Perl

1

Perl

20

Perl:

33

48

65

82

95

110

124

1-

Perl
Perl .
, . , , , , , 2000, ,
, , , Web.
Perl , (glue language),
. , Perl
, Perl, , . Perl
, , Web-. , ?
Perl .
, . Perl
HTML Web.
, Perl ,
. .
, . Perl ,
. , , , . , Perl
, ,
. .
. Perl. ( ),
, perl. -
.
perl. -, ,
Perl, PERL. Perl -

20

I. Perl

Practical Extraction and Report Language,


.
PERL, . Perl.
Perl .
Perl:
Pathologically Eclectic Rubbish Lister (
)
.
Perl.

Perl
Perl, .
Perl ( , )
, ,
. . ,
.

Perl ?
, ,
Perl . , Perl UNIX. Windows NT Perl
Windows NT Resource Kit. , Perl, .
UNIX .
, , .
, :
$
$ % bash%, , ,
.
. Perl .
, Perl , ( $ ):
$ perl -v
{ command
not found) Perl. , Perl , ,
.

1- . Perl

21

Perl , 5 5.004, 5.005, 5.6 .. Perl


4.x, . Perl
. , , , .
Perl 5.6.
Windows, ,
Perl, . MS-DOS,
. 1.1. ( :\>
):
C:\>perl -v
; 5 MS-DOS Piompl

. 1.1. Perl
MS-DOS

5, . DOS Bad command or
file name ( ), Perl
( 5).
, Perl Macintosh, File Find (Command-f)-
MacPerl, . 1.2. ,
Apple About MacPerl.
5.2.0 (Patchlevel 5.004), ,
MacPerl.

More Choice-.
. 1.2. Perl Macintosh
22

I. Perl

Perl Windows 95/98/NT


, Perl Windows .
, make-, , Perl . ,
. , 16- , " Perl",
. , ,
Perl Windows .
. ActiveState Tool Perl Windows, Windows. . 1.3
. Perl ActiveState.
http://www.activestate.com.
1

ActivePerl Build 613 Setup


Welcome to t h e ActivePerl
Build 6 1 3 S e t u p W i z a r d
The Setup Wizard will install ActivePerl Build 613 on your
computer, Click Next to continue or Cancel to exit ttie Setup
Wizard.

5.6.0 Build: 613 Built: 03/24/2000


'Cartel
. 1,3. ActiveState Perl Windows

- ActiveState Perl. Perl - Web- ActiveState.

Perl UNIX
Perl UNIX . ,
.
Download Web- http://www.perl.com.

1- . Perl

23

, "Stable" "Production".
ANSI . , ,
. Perl , ,
.
UNIX , Perl . , Perl Linux, Solaris,
AIX UNIX. .
Perl , ,
stable.tar.gz. Perl .
:
$ gunzip stable.tar.gz
$ tar xf stable.tar
- . gunzip, http://www.gnu.org. gzip.
:
$ sh Configure
Configure, .
, <Enter>. , .
, UNIX- Perl -
. Configure ,
$ make

. , . make , :
$ make test
t make install
, Perl . , root, #.
Perl .
make install , , Perl ,
$ perl -v
!
- Perl UNIX.
Perl http://www.perl.com.

24

I. Perl

Perl Macintosh
Perl Macintosh (MacPerl) Web-
http://www.perl.com. http://www.perl.cora/
CPAN/ports/mac. appl.bin , Stufflt Expander, .

Perl Shuck, MacPerl. MacOS 8
Internet Control Panel, Advanced^File
Mapping .pod Shuck. . , .ph, .pi, .plx, .pm, .cgi .xs, Perl, MacPerl. TEXT.
MacOS 7 InternetConfig. internetConfig Helpers
.pod Shuck, Perl MacPerl.
- MacPerl.
MacPerl
http://www.perl.com/CPAN/ports/mac.

: Perl Perl.
, ! . .
! Perl 5.6 1700 ! , , ( FAQ),
, Perl.
. Windows
UNIX Perl perldoc. . perldoc .
UNIX, DOS
.
$ perldoc perl
PERL(l)
User Contributed Perl Documentation

PERL(l)

NAME
perl - Practical Extraction and Report Language
SYNOPSIS
perl [
[
{
[
[

-sTuU ]
[ -hv ] [ -V[:configvarl ]
-cw ] [ -d[-.debugger] ] [ -D[number/list] ]
-pna ] [ -Fpattern ] [ -l[octal] J [ -0[octal] ]
-Idir ] [ -m[-]module ] [ -M[-]'module...' ]
-P ]
[ -S ]
[ -x[dir] )

1- . Perl

25

[ -i[extension] ]
[ -e 'command' ] [ ] [ programfile ] [ argument ] . . .
For ease of access, the Perl manual has been s p l i t up into
a number of sections:
, , : perlfunc ( Perl), perlop ( Perl) perlfaq (
Perl). perlfunc
perldoc perlfunc. perldoc perl.
, perldoc
-tf. ,
print:
$ perldoc -tf print
FAQ , Perl. ,
Perl, . ,
, FAQ.
FAQ, -q, , FAQ. , Perl, :
$ perldoc -q support
FAQ Who supports
Perl? Who develops it? Why is it free?


Perl UNIX- man-. Perl man . Perl
perldoc, man, UNIX:
$ man perl
Windows ActiveState Perl HTML,
Web-, . C:\Perl\html. Perl , html.
MacPerl Shuck, MacPerl. , . 1.4.

?
, .
-, , . perldoc , .
perldoc PATH. , . Perl , , Perl -

26

I. Perl

. , Perl
, .
, , ( ) Perl.
Perl Perl .
Illiew

Lookup...
ana...
MacPerl Oueruieu*
Table of contents
Macintosh specific feature*
MacPerl book information
Macintosh Toolbox Modules
Data structures
SgntaH
Operators and precedence
Regular expressions
Builtln functions
Predefined uarlobles
Rd anted Topics
Troubleshooting
Uarlaus

General Questions Rbout Perl


Obtaining and Learning about Perl
Programming Tools
Data Manipulation
Files and Formats
Regexps
General Perl Language Issues
System Interaction
Networking

MacPerl Homepage
The MatPerl Pages (PTFl

. 1.4. Shuck MacPerl


-
, Web-.
http://www.perl.com . ,
, Perl,
.


Perl, ,
. Notepad
() Microsoft Windows EDIT.EXE DOS. UNIX vi, emacs pico. , . MacPerl ,
File^New.
Perl .
( Microsoft Word, Wordpad, WordPerfect .) , . Perl
, , . , .

1- . Perl

27


:
JM/usr/bin/perl
print "Hello, World!\n";
f! .
,
hello. , ,
. Windows Macintosh
. - ,
.pi .plx.
hello.pl.


. UNIX
. Microsoft Windows MS-DOS. , hello,
cd.
. ( DOS,
UNIX .)
C:\PROGRAMS> perl hello
:
flello,

World!

, !
,
. ( , .)
- , .
Bad command or file name perl:
command not found, , perl,
PATH.

Can't open perl script hello: A file or directory does


not exist , hello ,
.

syntax error , Perl ,


, hello. , , ,
UNIX cat, DOS type. , .

Mac Perl, Run "hello"


Script, .
, Open
File, Run.

28

I. Perl

! ?
perl hello perl. perl. ", " Perl.
, (
hello), .
" " . , ,
Perl, .
perl ,
.
.
, hello.

Perl
hello
jf!/usr/bin/perl
Perl , #, . Perl . #! .
perl /usr/bin/perl. UNIX ,
, | ! , , . " "
. Web-,
Apache, #! perl.
, .
:
print "Hello, World!\n";
Perl, ,
Perl. print,
Hello, World! . . .
Perl ; -.
Perl , .
print Hello, World!. \ Perl ,
. , \, Perl , , .
.


Perl .
- .
,
. Perl
.

1- . Perl

29

, , . , : pr int
. , , 25 61 ,
2561. , , , "Hello, World!", . , . , :
f!/usr/bin/perl
print
"Hello, World!\n"
}
, .
Perl ,
. .
, , , -
. .
, , .
, Perl. , Perl
. peristyle.
Peri .
, , .
, ,
, , ! The Perl Journal (http://www.tpj.com) Perl- Obfuscated Perl Contest.
.

Perl , . . , Perl,
, . , ,
Perl , .


, Perl, ?
. , , . ,
, . Perl
- : " , , ".
.
Perl, , , , Perl.

30

I. Perl

?
.

-.
" " UNIX. ?
, #! Perl, , /usr/bin/perl , , /usr/local/bin/perl. chmod. hello UNIX
chmod +x hello. Perl
hello ./hello.
UNIX test, UNIX
.
. , ,
.
, -, if Perl .

perl _, , "
".


1. Perl , a perl :
) ;
) ;
) DOS.
2. Perl?
) http://www.microsoft.com
) http://www.perl.com
) http://www.perl.net
3. Perl?
) persyn
) perlop
) perlfaq

1- . Perl

31


1. ), , , perl DOS, ) .
2. ). .
3. ), , perldoc perl, ?

Peri.
, , FAQ.
Web-, ""
http://www.perl.com , .

32

I. Perl

2-

Perl:

, "",
. Perl , .
Perl. , , , , , ,
, , , , , .
Perl ( ) , , , . Perl , .. ,
.
. , ,
, g, 15- . Perl
.
Perl . , .
, , . ,
.
Perl.
Perl. Perl , .
.

().

2- . Perl:

33


Perl , :
.


. Perl "" ,
. , . 2.1,
Perl.

2.1.

12.5

15.

.7320508

lei0

,
( )
( , )

6.67-33
4_294_296

, , ,
, . .
. . ,
. , . , Perl
.
, , , 010. Perl
. Perl .
, perldata.


Perl .
.
.
ASCII , ASCII
. .
Perl, ,
. (quoting) . (' '), (" ")- :

34

I. Perl

"!"
' '
" \ ,\ 6,\ \"
" , .\"
, . , , Perl,
. , Perl :
" : " .""
,
. Perl .
, Perl
, , :
" : \" .\""
Perl, , .
, :
' V .'
,
. Perl. , , .
,
,
- . . 2.2 Perl.

2.2.

\
\
\t
\b
\u
\1
\\
V
V








. , Perl perldoc. perlop Quote
and Quote-like Operators.

2- . Perl:

35

, , :

" : \" \", : \"!\ ."


Perl
qq q. qq
, :
qq(H : " ", : "!".)
q:
q('' )
qq q
, -. (delimiters). , ,
, , -:
q/'' /
q,'' ,
, , qq q.
( h ) Oi (] , . ,
qq q, :
qffizo ( ) ( ).);
. ,
:
q[flxo ( ) ( ).];


Perl . . :
$
Stotal
$Date
$serial_number
$cat450
, , Perl, . , Perl ( ), . ,
(, ). Perl, , ..
, , , .

36

I. Perl


(az AZ),
.
.

. ,
, :
. :
$value
$VALUE
$Value

$valuE
, Perl . , $_, $", $/, $2 $$,
Perl-. .
, Perl .
. Perl , . (, ), 0 (), (..
), "" .

. Perl -w
( !) , . , Use of uninitialized value.

$_
Perl ,
, . $_. , print , $_:
$_="Dark Side of the Moon";
print; $_, "Dark Side . . . "
$_ , ,
.
,
6- , " ".
$_, .

2- . Perl:

37


, - Perl. Perl , , , , , 3- , " ".
Perl 2.1.

2.1. Perl
1: jfi/usr/bin/perl -w
2:
3: ?radius=50;
4:
5: $area=3.14159*(Sradius ** 2);
6: print $area;
' .

1. ,
Perl. -w , .

3. .
$radius 50.

5. . . $radius, * ** (
) 2. $ .

6. , $.

, . , 2 , 54*$r, "Java", sin($pi*8) $t=6. . , , , . ,


Perl.


2.1, =. ,
, , . :
$.=" ";
$pi=3.14159;
, , , , .. . ,

38

I. Perl

. ,
$, $ $ 42:
$=$=$=42;
$ 42, $
$=42 ( 42). $ $=42. , , , :
$=89*$;
$count=$count+l;

$ $count.
Perl . .


Perl ,
. ,
. . . 2.3 .

2.3.

5 + $t

5 $t

Sy - $

$ $

$ * $pi

$ $pi

$f /

$f 6

24 % 5

24 5 (4)

4 ** 2

, : , , , . ;
, .
:
5*6+9;
# 39
5*{+9);
I 75
5+{6*(4-3)); * 11


Perl , .
, , (.) , , ,
, :

2- . Perl:

39

$=", !";
$=" ";
$=$ . $;
$ $ . $ , !
, $ $ .
. ,
, , Perl "" .
. ,
, :
$="";
print ", $name!";
Perl , $name . . ,
( Perl )
, :
$name="Ringo";
print ' Sname'; f He "Ringo"
print " \$name"; $ "Ringo"
print $name, Sname . ,
:
$fruitl="a6noKH";

$fruit2="H ";
$bowl="$fruitl $fruit2";
, Perl ,
{}. Perl
, :
$name="Thurs";
print "I went to the fair on ${date}day";
, Perl
$date $dateday. , $date.
.
, , . :
$line="-" 70;
"-" 70 . $line.


Perl ,
, . Perl.

40

I. Perl


.
6/3 3, 5*2 5 2
.. ().
,
(-). , :
6;
-6
-(-5)

I
f
f , .

, Perl .
(
. 2.4 ).
Perl , , .. , Perl.
. 2.4.

2.4. Perl

int
length
lc


int(5.6234)
lengthf'nose"1
lc("ME TOO")

uc

ucf'hal 9000";

,
("HAL 9000")

COS
rand

cos(50)

50 (.964966).

rand(5)


0 ; 0 1

(5)
- (4)

("me too")

Perl. 1 , " Perl", , perldoc, Perl.


perlop perlfunc.
, ,
.


" "
, , :
$counter-$counter+l;
-,
(, ). -

2- . Perl:

41

, (++). :
$counter++;
$counter
.
Perl , ,
, (--).
, :
$countdown=10;
$countdpwn; I 9
,
. - ,
! ( )
1, . .
$="999";
$++;
print $a;
$=9";
$++;
print $;
$a="zzz";
$++;
print $a;

# , 1000.

\ dO. 9+1=10,
\ d.

t .
1 .


( ) , - "", , (
5- , " "). , , , 5- .
: <STDIN>.
Perl, . , <STDIN> , , :
print " ? ";
$size=<STDIN>;
print " ~ ${size}CnacH6o ";

42

I. Perl

(, 45) :
? 45
45

<STDIN> , <Enter>. Ssize. , <STDIN>, , <Enter>. , , .. .
chomp:
print ' ? ";
$size=<STDIN>;
chomp $size;
print " $size. \";
chomp - .
1, ,
.


,
=. Perl . Perl
, . :

:
=

, . ,
$=$+3;

$+=3;
:
$line.=" - "; I $line;
$*=$ t To , $=$*$

$*=67 $ $ 67 $


Perl , . , , Perl . , -.

2- . Perl:

43

, Perl ,
:
$=42;
I
print $a+18; * 60
$="50";
. *
print $b-10;
# 40
, Perl , :
$=42/3;
I

$=$ , "Hello"; #
Print $a;
"HHello"

, , Perl 0, :
$a="Hello, World!";

print $a+6; I 6

, ,
Perl .
, Perl,
" ". , , Perl .
, -v
, Perl , , : Argument X i s n ' t numeric.

:
. , ,
. :

/.

_.

\ -\ \


,
(1 +
_ ) 2.2, interest. . interest
_
, ,
1- .
,
perl interest
2.3 interest.

2.2. interest
1: /usr/bin/perl -v
2:

3: print " ? ";


4: $pmt=<STDIN>;
5: chomp $pmt;
6:
44

I. Perl

7: print " ? ( 7% .07) ";


8: $interest=<STDIH>;
9: chomp $interest;
10:
11:print ' ? ";
12:$mons=<STDIN>;
13:chomp $mons;
14:
15:f
16:$interest/=12;
17:

18:$total=$pmt * ( ( 1 + $interest) ** ($mons -1) )/ Sinterest;


19:

2 0 : p r i n t " $mons $interest \n";


21:print " $total.\n";

I. if .
1. ( )
-w. !
3. .
4. $pmt ().
5. $pmt.
7~9. $interest
.
1113. $mons .
16. $interest 12, $interest.
18. , Stotal.
2021. .

2.3, interest
1: ? 180
2: ? ( 7% .07) .07
3: ? 120
4: 120 0.00583333333333333
5: 61652.767054031.

2- . Pert:

45


, Perl .
.
. ,
. . Perl , .


interest . , ?
printf (), 9- , " ".
Perl ?
printf () .
round{), POSIX, ,
.
Perl?
, .
Intel- UNIX 300- .
14 .


1. qq :
) ;
) .
2. $ :
$=6;
$++;
$=$;
$-;
$=$;
) 6;
6)7;
) 8.

46

I. Perl

3. (.):
) ;

) .

1. ). qq . ,
.
2. ). 5 , 7 $.
$ 6 $.
3. ). Perl
.
, :
qq($a$b$c);

,
.

32 5/9. , 75 21,1 .
interest , .
printf (), , int.

2- . Perl:

47

3-

2- , " Perl: ", . , .


, . , Perl .
Perl, , , .
. , - .

: , ,
, , . ,
. .
, ,
.
.

48

Perl .

I. Perl


Perl .
:
{
_;
_6;
_;
}

, . , :
{
;
i
_6;
;

Perl , , .
, . ,
, :
{ ;
{ _; }
{ _;

,
. , Perl .
Perl . Perl.

if
Perl if. :

if ()
if : , .
, . :
if < $ - 5 ) {

print ' $ 5.';


}
$ 5. (
== ; =.) ( $ 5) , print. $ 5, print .

3- .

49

if , , .
if-else.
if

() f ...

# . .
Else

t .

, , , ,
else .
:
$r=<STDIN>; chomp $r;
if ($r == 10) {
print '$r 10';
} else {
print '$r 10...';
$=10;
print '$r 10';

, $ =. $
==. . , . , = ,
== .
if, ,
:
if (!)
1
elseif {2)
2
else

1 ...
.. .
, 2 ...
.. .
,
.

: ,
!, !.
elseif 2. !, 2
, .
Perl:
$=10;
if ($r == 10) {
print '$ 10!';
} elseif ($r == 20) {
print '$r 20!';
} else {
print '$r 10, 20';

50

I. Perl


==.
Perl , , . 3.1.

3.1.

$ == $

, $ $

==
>

?>$

, $ $

<

$<$

, $ $

>=

$ >= $

, $ $

<=

$ <= $

, $ $

!=

$ != $

, $ $


, if, 3.1.

3.1.
1: #!/usr/bin/perl ^w
2:
3: $im_thinking_of=int(rand 10);
4: print " 0 9:";
5: $guess=<STDIN>;
6: chomp $guess; i Be !
7:
8: if ($guess>$im_thinking_of) {
:
print "1\";
10: } elsif {$guess < $im_thinking_of) {
11:
print "!\";
12: } else {
13:

print " ";

14:}

.
1. Perl.
-, -w . 1- , " Perl",
, .
3. rand 10 0
10, int() .
0 9 $im_thinking_of.
46. , $guess. chomp
.

3- .

51

89. $guess ,
$im_thinking_of, .

1011. $guess , $im_thinking_of, .

12~13. .

. 3.1 .
. :
$first="Simon";
$last*"simple";
if ($first == $last) { t == - , !
Print " !\";
}

, $first $last . 1- , " Perl", , , Perl ,


.
if Perl : if { 0 == 0 ). ,
if , , , .
,
( Simon simple) ==
.
Perl, . 3.2.

3.2.

eq

$s eq $t

,
$s $t

gt

$s gt $t

,
Ss $t

If

$s I t $t

,
Ss $t

$s ge $t

,
$s $t

$s le $t

,
$s $t

$s ne $t

,
$s $t

52

I. Perl


ASCII- , . , ,
, .
, , ,
, , . , 1506 Happy, ,
, happy.

Perl
: " ...", . Perl , , . :
0 ;

("") "0" ;

undef ;

, ? , ,
, : .
, .
. 3.3.
, , .

3.3.

. 0

10

9>8

. ,

-5+5
0.00
""
"

. 0,
. 0, 0x0, 00,
.

"0.00"

. ,
. ? , "" "0"

"00"

"0.00"+

. , 0

if , , , , .
$

if ($a) { . . . }

3- .

53

J $. ,
- .
If (length(Sb)) { .... }
Perl undef. . , . undef Perl .
. , if, undef
. undef
0.

. Perl
undef
Use of uninitialized value.


, , -,
$ $ , a $z . if:
if ($ ) {

if

if ($z) {
#
} else {
print " . \

Perl , . ,
. 3.4.

3.4.

54

and

$s s& $t

,
$s $t

$q
$

,
$q $
, $s
$t

or

and

$s 11 $t

I. Perl

.3.4

not

$q or $p

, $
$

! $

, $

not $m

, $

. 3.4
:
if ($x and $y and not $z) {
print " . \";
, ,
, ( 3.2).

3.2.
$=0; $b=l; $c=2; $d="";
if {$a and $b) { print ' $ $b '; }
if ($d or $b) { print ' $d $ '; }
if {$d or not $b or $c)
{ print ' $d , $ , $ ';

.
1. .
3. $. , and
. $ , ,
. print .
4. $d.
, or , $, , ,
, , print .
5. $d.
, , ,
, 4, or. -

3- .

55

$b , not $b . , $. , , , print .
,
,
, . . Perl if:
$message=' $ $ .';
($ and $b) or $message="OflHa $ $ .";
, $ $ ,
or, $message . , or
, or .
Smessage . or and $message.
, [ | or . ,
| [ , or. , 11, , .
/and, l/not. , .
.
, Perl . . ,
5 & 7 7 ( ),
. .
$nev ,
$old.
f "default".
$new=$old jj "default";
, :
$new=$old;

if {I $old) { I $old ?
$new="default";

, , .
. , 3.1, -

56

I. Perl

. . ,
.

while
while . while
, . :
while {)

Perl while, . , .
, 1 ,
( 3.3).

3.3. while
1: $counter=0;
2: while ($counter < 10 ) {
3: print " $counter \";
4:
$counter++;
5: }
.

1. $counter .

2. Scounter < 10. , .

4. $counter .
5. } , 2 {.
Perl while
.

for
for ,
Perl. :
for (; ; )
for, , ,
. Perl for, .
.

, . .

3- .

57

. - ,
. , .

for:

for ( $=0; $<10; $=$+2 J {


print " $\";
}
$ 0, $<10, . . $ 2: $=$+2. .
, $ 10. , .
for ,
, , . ,
for , . , for
:
$1=10;

for { ; $i>-l; ) {
print "$i..";

$ij
I .
}
print " 1\";


, . , Perl
while, for,
if . .
.

if
if . , if. ,
if (__) {;}

:
if

( );

:
$correct=l if ($guess == $question);

print " pil" if ( $ratio != 3.14159);

58

I. Perl

Perl , ,
. if , .


, for, while, if, , Perl .
last. . :
whiltf ($i<15) {
last if ($i==5);

last while, $i 5. , .
last .
3.4 100, 140, 2 70, 4 35 . . , last.
, $j. ( $i) .

3,4.
1: for{$i=0; $i<100;
2: for($j=0; $j<100;
3:
if <$i * $j == 140) {
4:
5:
6:
7:
3: }

print " $i $j 140\n


last;

>

last, Perl next. , :


for <$i=0; $i<100; $i++) {
next if (not $i % 2);
print " =$i ";
}
0 100. next
, $i .
$i % 2 $i 2, not . , , print . ,
, next.

3- .

59


Perl (for while).
,
, :
MYBLOCK:

MYBLOCK. ,
, : , %, $, $. ,
Perl.
. Perl. for
while , :
OUTER: while (?expr ) {
INNER: while ($expr) {
;

, last next.
. 3.4 , 140,
for. , . , - .
, ! . :
OUTER: for($i=0; $i<100; $i++) {
for($j=0; $j<100; $j++) {
if ($i * 55 == 140) {

print " $i $j 140\n";


last OUTER;

last , , ,
OUTER.
, 140.

Perl
exit .
Perl , .
, .
11- , " ". , 0 , .
exit:

60

I. Perl

if ($user_response eq '') {
print " .\'
exit 0;

exit ,
.
, Perl Perl .



?
, . , 1 , : 2 - , 3 , 4 ( 1, 4 2).

.
, 3.5, primes. He . , , 1- .
, :
perl primes

3.5.
1: #!/usr/bin/perl -w
2:
3: $maxprimes=20; t 20
4: $value=l;
5: $count=0;
~~~~
6: while(Scount < $maxprimes) {
7:
$value++;
8:
$composite=0;
9: OUTER: for($i=2; $i<$value; $i++) {
10:
for{$j=$i; $j<$value; $j++) {
11:
if (($j*$i)==$value) {
12:
$composite=l;
13:
last OUTER;
14:
}
IS:
>
16:
}
17: if (1 $composite) {
18:
$count++;
19:
print " $value \";
20:
}
21: }
3- .

61

1. ( ) -w. !

3. $maxprimes
, .

4. $value ,
.

5. $count .

6. while , .

7. $value , ^
2.

8. $composite for .
, .

910. for $value. , 4 2 2, 2


3, 3 2, 3 3.

11-14. $i $j . $value,
$composite .

1720. $composite.
, .
.
. , ,
.

Perl.
, if ,

. , while, until for,
. Perl .

62

I. Perl


. Perl
switch case?
! Perl ,
switch. ,
:
if [$_ == $1) {
1;
} elseif {$_ == $2) {
2;

} else {

__;

>
Perl, , perdoc perlsyn, switch, switch-
.
for while,
if ?
, , .
, .
? Perl ,
Unmatched right bracket ( Hissing right bracket).
.
, { } . Perl , , . Perl
, . ( vi, Emacs MultiEdit) ,
. .

1. while , .
, ?
) if (not . . . ) {}
) while (! ) {}
2. ?
( and 5) || (( "" or 0 or "") and (6 and "Bello")) or 1

3- .

63

) ;
) .
3. $i ?
for ($i=0; $i<=10; $i++) {
a) 10;

6)9;
) .

1. ). while (! ) {} , .
2. ). :

() || (() and ()) or


|| or

3. ). $i<=10, ,
, $i 11. ,
. , , , .

, 3.1, , .
, 3.5, . , 2, , . .

64

I. Perl

4-

:

Perl .
, , , .
, , , 50
.
Perl . : ,
.
,
.
, . . (2, 5, $, "Bob") , , $
"Bob". .
, .
,
, .
. Perl , ,
@. , @F00 -
Perl. , $names . , .
.
, , .
(, 8F00,
gnames . .).
Perl , , . 7- , "".
.

4- . :

65



. :
(5, '', $, 3.14159)
, 5,
'', $ .
, , Perl gw;

qv ( 45.6 $ )
.
, . , $ , .. '$', $,
. , qw . :
('', '', '45.6', '$')
, $ . qw
, ,
. , '$' $, .
Perl
. (..).
:
(1..10)
, , (
1 10 ). :
(1.-10, 20..30);
21 : 1 10 20
30 . , ,
{10..1), .
, . (a..z) , 26 . (aa..zz)
, 675 , ,
ab, ad - zx, zy, zz.

66

I. Perl



, . Perl , - . , .
:

boys=qw { );
. , = ,
. 8boys : , . qw, . :

%=original;
1=();
((original (.
dcopy , .
Sclean.
.
, ,
, :
Gboys=qw ( );
i!girls=qw( );
kids=(8boys, Sgirls);
$family={!Jcids, {'', ''), '');
{Oboys, ggirls) Perl
(, ..) , Gkids.
Skids ('', '') , ^family.
@boys, Sgirls, Gkids ('', '') ^family, , . , Ofamily :
(!!.1=*( );
,
. :
($, $b, $c) = qv( );
'', $ ''
$ ''. , ""
. :
($a,@iruit,$c)=gw(nepcHKH );

4- . :

67

$ ''.
Ofruit. $
, "" @fruit. $ (undef).
, , , undef. , , .
:

($t,$u,$v)=qw(

undef
($a,$b,$c,$d)=qw(

$t, $u $v , .
('') .
$ , $ $ , , $d " " (
'' $). , $d (undef).


.
. , ,
.

:

print "";
garray, .
. 0 1. , :
trees

.
$_{].
. .
:

68

I. Perl

trees=qv{ );
print $trees[O]; f ""
print $trees[3]; I "".
$trees[4]='C0CHa';
, $trees, $.
, . $ $trees[3] , , Gtrees. , . .
,
, . Perl Strees $trees[0], . , Gtrees, $trees.
Perl , (slice).
6, ,
, :
etrees=qv{ );
Strees[3,4,6];
I
0conifers=trees[5,7]
I


, .
. Perl
. _.
, :
Ctrees-qv{ );
print $#trees;
, ,
, 7. SJftrees
. , .
(undef).

(.. , ), :
$size=Carray;
$size darray.
, Perl.
.
,
, . ,
$[-1] , $(-2]
..

4- . :

69


? ,
, . , , - .
. , , , :

, .
.
Perl . Perl
- . Perl
. , ( =)
, . ,
( ), , . :

$a=$b;
i , .
8foo=bar; f , .
($a)=?foo; t , .
$=;
# , .
,
.
, $ $
( ,
):

efoo-qv{ );
$=;
$b=$|foo;
print "$a\n";
print "$\";
$ 4, $ 3.
? Ofoo
, $. $
( ,
).
, , , :
0mydata=qw{ );
if (fcnydata) {
print " 1\";

}
Smydata ,
, 4.
if 4, , .

70

I. Perl

gmydata , , .
. , Perl , if.
, (void), 9- , " ".


Perl . . , .
print . ,
. print f!foo, , ,
:
print Gfoo;

scalar:
print scalar(Gfoo);
8foo. scalar
ifoo, , print.
2- , " Perl: ",
chomp , .
- . , -
.
, , ,
<STDIN>. Perl, ,
, -. . , , . :
$a=<STDIN>;

f ,
# $ .
evhole=<STDIN>; f ,
* gwhole.
($a)=<STDIN>;
# ,
I .

$ ? ,
, ,
, , , . ,
, $ .

4- . :

71

?
Perl, .
(EOF). , . UNIX <Ctri+D>, . MS-DOS Windows
<Ctrl+Z>,
, , 1- , " Perl",
.
, , . 100 :
Gstars= *") 100;
"*" , , . .
, , (,). , :
Gpets=('', '', '', '', '');
, .
.
, :

$last_pet=('', '', '', '', '');


f , !
, , Perl . , (- $last_pet, ). $last_pet
''.
local time, , . localtime . , print
scalar(localtime) - Thu Apr 13 10:14:45 2000.
localtime , :
($sec, $min, $hour, $mday, $, $year_off, $wday, $yday, $isdst)=localtime;
. 4.1.

4.1. localtime

$sec

, 0-59

$min

, 0-59

$hour

, 0-23

$mday
72

, 1-28, 29, 30 31

I. Perl

. 4.1

$mday

, 1-28, 29, 30 31

$mon

, 0-.11 ( !)

Syearoff

, 1900 . 1900,

$wday

, 0-6

$yday

, 0-364 365

$isdst

,
2000 Perl $year_off,
localtime. ,
'19'. ,
1900 1999 99, 2000 100.
1900
2000 . Perl Y2K, $year_off '19' '20'
.

, ? , .
.
,
.


, ,
.


3- , " ", while, for . , , , .
for, :
flavors=qw( };
for ($index=0; $index<eflavors; $index++) {
print " $flavors($index)";
print ", .\";
. qw. ,
, -, -

4- . :

73

. - $index 0
, flavors. ^flavors 5 .
, , , ? Perl , . . Perl , , foreach.
foreach , , . :
foreach Scone (^flavors) {

print " $\";


>
. $
lavors. $
^flavors, , . , foreach
. ,
$
gflavors. :
foreach $flavor (flavors) {
$flavor="$flavor "; # flavors!

Print " $flavor";


}
$flavor
. "
", .
, @flavors .
Perl foreach for . . foreachf)
, for() ,
3- , " ".
, .



Perl .
. split. , , ( ).

ewords=split(/ /, " ");

74

I. Perl

Swords , ,
. ,
$_. split , $_. - . '' ( ),
, :
while (<STDIN>) {
.
($firstchar)=split(//, $_);
print " $firstchar\n";
>
$_. $_ . . split
, $_. , . $firstchar, .
split . ,
6- , " ". , , ..
,
split.
Perl.
, , ,
, :
8Music=('White Album,Beatles',
'Graceland,Paul Simon',
'A Boy Named Sue, Goo Goo Dolls');
foreach $record {GMusic) {
($recordjiame, $ a r t i s t ) = s p l i t { / , / , $record);
}

,
, .
.
, . Perl join.
- , . :
Snumber=join(',', (1..10));
$number 1,2,3,4,5,6,7,8,9,10.
split join , :
$message="TyT ";
print " \"$message\" : " ,
$message));

4- . :

75

$message
split. join ,
.
:
" " :--- ---- ----


. ,
Perl ,
. Perl sort,
. , . .
:
Chiefs=qw(KniiHTOH );
print join(' ', sort echiefs);
: . , ASCII. ,
. , . . ,
11 100. ,
.
sort .
.
$ $, . -1, 0 1, $
$, $ $ $ $ . . ^numbers ,
.
0sorted=sort { return(l) if ($a>$b);
return (0) if ($a==$b);
return(-l) if ($a<$b);} ?numbers;
, , ,
. , Perl
,
" " <=>. - ,
( ). -1,
, 0 , 1 ~ :
sorted=sort { $a<=>$b;> ^numbers;
, . " "
.
, .
,
.
4 Perl FAQ.

76

I. Perl

, , reverse.
. . . ,
reverse( "Perl" ) lreP.
reverse , :
f!lines=qw(He );
print j o i n f ' reverse sort Glines);
sort, {, , , , , ).
reverse join . .
. , ?

:
, ,
. , -
. ,
. , ,
.
, 4.1, Hangman. , , 1- .
,
perl Hangman
4.2 Hangman.

4.1. Hangman
1: l!/usr/bin/perl -w
2:

3: ewords=qw{ );
4: $guesses[0]="";
5: $wrong=0j
6:
7: $choice=$words[rand Bwords];
8: $hangman="O-j<";
:

10:eietters=split(//, $choice);
ll:$hangman=split{//, $hangman);
12:Sblankword=(0) x scalar(ehangman);
13:OUTER:
14: while ($wrong<hangman) {
15:
foreach $i (0..$Hetters) {
16:
if ($blankword[$i]) {
17:
print $blankword[$i];
18:
} else {
19:
print '-";
20:
}
21:
}

4- . :

77

22:
print "\n";
23:
if (Swrong) {
24:
print dhangman{0..$vrong-lJ
25:
)
26:
print "\n : ";
27:
$guess=<STDIH>; chomp Sguess;
28:
foreach(Sguesses) {
29:
next OUTER if ($_ eq $guess);
30:
}
31:
$guesses[$tguesses]=$guess;
32:
$right=0;
33:
for ($i=0; $i<81etters; $i++) {
34:
if ($letters[$ij eq $guess) {
35:.
$blankword[$i]=$guess;
36:
$right=l;
37:
}
38:
}
39:
$wrong++ unless($right);
40:
if (join(", Gblankword) eq Schoice) {
41:
print " 1\";
42:
exit;
43:,
}
44: }
45: print "$hangman\n , $choice.\n";

^ .
1. (
) -w.
!
3. Swords .
4-5. . ^guesses
. $wrong
.
7. @words $choice. rand{)
, Swords .
Swords Swords, 4. rand 0 4,
.
.
8. .
10. ,
dletters.
11. ,
^hangman. $hangman[0]' , $hangman[l] ..

78

I. Perl

12. Gblankword . Gblankword {0}


scalar(Ghangman), Ghangman.
. 35 .
1314. . OUTER," .
,
.
1521. foreach Gblankword,
, .
2325. $wrong . , $wrong hangman.

2627. . chomp .

28-30. , .
, 13. .
.

31. Gguesses.

3238. . ^letters,
, . , (iblankwords.
Sblankwords , . $right
1, .

39. $wrong .

4043. blankwords , . ,
.

45. , . .

4.2. Hangman
:

4- . :

79

0 :
-
0 :
-
0 :

0 :


, , split join,
foreach. ,
.

Perl. .
. Perl , ,
. Perl
. - .


?
. ,
, 7- .
?
?
, ?
: . . 7- .


1. $ $.
) $=$;
) ($,$)=($,$);
) $=$; $=$; $=$;

80

I. Perl

2. $
$a=scalar(array); ?
) ?;
) ;
) .

1. ). , $ . ) , .
) .
2. ).
.
$#. scalar
,
. flarray.

Hangman , .

4- . :

81

5-

.
, , .
!
Perl . Perl ,
, , , .
, Perl, .
Perl -. -. , .
.

"" .


Perl . Perl.
. , (
/ ), , .
STDIN.

( STDIN).

82

I. Perl

, Perl.
2- , " Perl: ". , ($, @ - ). ,
Perl, foreach, else, if ..
, . . .
: perlfunc, open.
, ,
. , , open:
open {_6, )

open , .
, , ,
, :/windows/system/, open
. open
(), undef (), :
if (open{HYFILE, "mydatafile")) {

t
} else {
print " mydatafileUn";
exit 1;
}

open , MYFILE if.


, else, .
Perl " "
die. die :
Died at ^ line xxx
Perl, xxx ,
die. die open
:
open(MYTEXT, "novel.txt") || die;
, . open , ,
(| | ) . ,
( die). open .
or.

5- .

83

.
. , ,
, , ( ). , . . close:
close(HYTEXT);
, open
, , .

, , novel.txt.
Perl ,
. , .
, .
, .
:
open(MYFILE, "DISK5:[USER.PIERCE.NOVEL]") || die;
open(MYFILE, "Drive:folder:") II die;
open(MYFILE, "/usr/pierce/novel") || die;

I VMS
f Macintosh
f UNIX.

Windows MS-DOS , \Windows\users\pierse\novel.txt. , , ,


, .
:

open (MYFILE, "\Windows\users\pierse\novel.txt ") || die; t !


, \
, ,
Perl. :
open (MYFILE, "\\Windows\\users\\pierse\\novel.txt ") j| die;

i ,

, (/)
Windows MS-DOS ( Windows MS-DOS ):
open (MYFILE, "/Windows/users/pierse/novel.txt ") || die;

(/home/foo UNIX c:/windows/win.ini


Windows), (,,/junkfile UNIX . ./bobdir/bobsfile.txt
Windows). open Windows , UNC (Universal Naming Convention).
UNC :
\_\ _

84

I. Pert

Perl , UNC ,
, ,
, :
open (REMOTE, "//fileserver/common/foofile") || die;
Macintosh , , , . 5.1.

5.1. MacPerl

Macintosh
System:Utils:config

, Utils, config

MyStuff:friends

MyStuf f , friends

ShoppingList

, , ShoppingList


. : " !" "
- ".
; , . . .
.
. (Frederic P. Brooks) The Mythical Man-Month {Addison Wesley, 1975, . 14) : " . , () , , , ... , , ".

( , ..)
, .
. , , .
, ,
.
. "" , .
, , , ,
. , , , .
, , ,
.

5- .

85

,
die Perl
. ,
die :
Died at _ l i n e xxx
die ,
.
, at _ line xxx, :
die " ";
# " at line xxx'
die " \"; t " "
Perl $!,
, (, - ). $! . $!
, :
open(HYFILE, "myfile") || die " myfile: $!\n";
- ,
myfile: a file or directory in the path does not exist.
, . ,
, .
.
$!
. (, -)
. $!
.

. warn,
die, , :
if {! open{MYFILE( "output")) {
warn " output: $1";
} else {
: f ...


Perl , . , ( ) . , :
open(MYFILE, "myfile") || die " myfile: $1";
$line=<KYFILE>;
I

86

I. Perl

.
, undef.
, . UNIX
(ASCII- 10), DOS Windows
(ASCII-: 13 10).
Perl,
.
12- , " .

( , MYFILE ):
while (defined($a=<MYFILE>)) {
print $a;
}
while.
while , Perl
$_ ,
:
while(<MYFILE>) {
print $_;
}
while $_ .
while ,
.
, , , . ,
chomp, .
. , :
open(MYFILE, "novel.txt")
contents=<MYFILE>;
close(MYFILE);

|| die " $ ! " ;

MYFILE
novel.txt {(contents. novel.txt
^contents: $contents [ 0 ]. $contents[l] ..
( ) .
, . , , . 5.1 .

5- .

87

5.1.
1: #!/usr/bin/perl -w
2:
3: open(MYFILE, "testfile") j| die " testfile: $1";
4: estuff=<MYFILE>;
5: close{MYFILE);
6: f .
7: foreach{reverse(stuff)) {
8:
print scalar(reverse($_));
9=
testfile :

,
.
5.1 :


,
.

I. (
) -w.
!

3. testfile,
MYFILE. ,
die, .

4. testfile Sstuff.

5. testfile ,
MYFILE.

7. (Jstuff
.., foreach.
$_, foreach.

8. ( $_), . scalar
, print , reverse . $_
. scalar
reverse, $_.
.
, , Perl .

I. Perl

Perl ,
Out of memory! . , .


. , :
open{,
(,

"> )

' )

, > .
Perl, , , . .
Perl, , ,
. :
,
open(NEWH, ">output.txt") || die " output.txt: $!";
t .
open(APPFH, " l o g f i l e . t x t " ) || die " logfile.txt: $!";
Perl - . , , ,
, .
(Windows 9x )
, .
, . , >, . , , , .
, , .
,
, , . close ,
, :
close(NEHFH);
close(APPFH);
, .
print. print
.
. print, , :
p r i n t

5- .

89

, ,
, .
, print . ,' . Perl,' , print,
, . ,
Peri : No comma allowed after filehandle (
).
:
open (LOGF, "logfile") || die $!";

if (! Print LOGF " ", scalar(localtime), "\n") {


warn " logfile: $!";
}
close(LOGF);

logfile .
print LOGF. , print,
, , , .
.
,
:
open(SOORCE, "soursefile")
open(DEST, ">destination")

contents=<SODRCE>;
print DEST $contents;
close(DEST);
close(SOURCE);

die $!";
die "$!";

# ""
I

. , , :
print DEST <SOURCE>;
print ,
<SOURCE> . , print DEST.

,

,
, .
, ,
. , , . Perl ,
, , .
, .

90

I. Perl


Perl UNIX. , UNIX, .
Perl : STDOUT
( ), STDIN ( )
STDERR
( ). .
Perl STDIN:
Sguess=<STDIN>;
print,
STDOUT, :
print " !\";
print STDOUT " !\";

# , . . .

12- , " Perl", ,


, print.
STDERR . . UNIX *
. ,
STDERR. , die warn STDERR. , , ,
DOS Windows, STDERR STDOUT.
UNIX
. -.
- UNIX.


, VMS, Atari ST Windows DOS, () . , Perl . , , . ,
, , .
, Perl \
, . UNIX \n ASCII- 10 ( LF), Macintosh Windows ASCII- 13 10
(CRLF). .
, GIF, EXE, MS Word
.., . , Perl,
,
binmode. . binmode , , . :
open(FH, "camel.gif") j | die " $ ! " ;

binmode(FB);

t .

5- .

91

t GIF-...
print FH "GIF87a\056\001\045\015\000";
close(FH);
binmode
. binmode. biimode ,
(, UNIX), .


, , ,
, , permission denied. Perl . :

-X _
-X
X , _
. . . 5.2
.

5.2.

- ''

,
''

-w

-w $a

,
, $

-e ''

, ''

-z

-z ''

, '' ,

-s

-s ''

'' ,

-f

-i ''

, '' ( )

-d

-d ''

-T

-T ''

!, ''
, ''

-B

- ''

, ''

-H

- '1

''

.
perldoc perlfunc Alphabetical List of
Perl Functions.

92

I. Perl


. , .
.
:
print " ?";
$filename=<STDIN>;
chomp $filename;
if (-s $filename ) {
warn " $file !\";
warn " ",
- $filename, " .\"


open close. <>
read, print. ,
binmode.
, , .


open . ?
-, open. , . ,
open. ,
> , . ,
open() j| die "$!";?.
die .
, . ?
, ?
, , .
, :
open(FB, ">c:\temp\notes.txt") || die " $ ! " ; # !
: ()( CTpoKa)otes.txt.
, . open. Perl "" , , .
open, permission
denied. ?
Perl , . ,
, Perl .

5- .

93

getc.
,
. Perl 15- , " Perl" FAQ, 16- ,
" Perl", FAQ.

. .

?

. 15- , " Perl". ,


!


1. data , :
) open(FH, "data", write);
) open(FH, "data"); FH
) openfFH, ">data") 11 die " data: $!";
2. (- $file > I and -s $) , :
) $ , ,
;
) ;
) $ , .

1. ). ) ,
) . ) , , .
2. ). - ,
( >1 , ), -s , .

Hangman, ,
, .

94

I. Perl

6-

. ,
. , ,
-, split, ,
, .
, , , , . Perl, . ,
.
. .
.
( .
) Perl {
perlre). , .
Perl
(Jeffrey E. F. FreidI) Mastering Regular Expressions
(Sebastopol: O'Reilly, 1997).
Perl, Perl .
, TCL, JavaScript, Python ,
UNIX. Perl ,
.
.

- .

95


Perl , / :
/ Simon/
S-i-m-o-n.
? , Perl $_. , $_, ( ). , S-i-m-o-n $_.
$_ , , //
. , :
if (m/Piglet/) {
I "Piglet" $_
}
,
. ( )
. , . :

$ ( ) \ | 0 [ { ? . + *

. , ,
:
m/ \$10/; I $ "$" ,
.
//. , :
if {m,Waldo,) { print " Waldo.\n"j}
, ,
. , :
if (m/\/usr\/local\/bin\/hangman/) {print " hangman!';}
:
if (m:/usr/local/bin/hangman:) {print " hangman!";}
,
. , m/Cheetos/
/Cheetos/. , -,
.
. , Perl ,
.
. , if, :

96

I. Perl

$pat=<STDIN>; chomp $pat;


$_=", ";
if (/$pat/){ f ,
print " \"$_\" $pat\n";

RE . - .


Perl, ,
. . ,
. .
.
, , ( ) , ,
.

.
, , . ,
. ...

, . , Perl
,
.
" " .

, , . , ,
. ,
.
,
, . .


(.) , . ,
/p.t/ . pot,
pat, pit, carpet, python pup_tent. .
apt expect , t
, .

6' .

97


,
:

/\\$/; *
, . 2- , " Perl:
", , .
, . 6.1.

6.1.

\t

\f

,
. , /Simon/ S S, i /, m .. ,

.
( ).
+. ,

. (
), . , /do+g/ :

Hounddog
hotdog
doogie howser
doooooooooooogdoog

we
badge ( )
doof us ( g)
Doogie (D d)
pagoda ( d, on g )

* +. * ,
. , /t*/ , ,
, .. /car*t/ :

98

I. Perl

carted

carrot ( )

cat

carl ( t )

carrrt

caart ( )

?.
( ). ,
/c?ola/ , .
, ola, cola.
? * , , ,
/c?ola/ ola, cola, ccola.
. /c*ola/ cola, ola, ccola,
, ,
.
+, *, ? , {} :
pat{n,m}
, , a pat ,
. ,
! :
/{5,10}/
/{9, }/
/{0, 4}/
/{8}/

* 5 , 10
i 9
4 ,

# 8

.*. ,
, /first. *last/ ,
. , Perl first,
last. :
then last
The good players get picked f i r s t , the bad l a s t .
The f i r s t shall be l a s t , and the l a s t shall be f i r s t .
. ,
, first last
last. * ,
" ": ,
. , , Perl.
perlre.


, .
, , Von
Beethoven von Beethoven " v, V".
- .

99

Perl .
. [ ].
.
( ), . . 6.2 .

6.2.

[abcde]

, , , d

[ - 1

, , , , d

[Gg]

[0-9]

[0-9]+

[A-Za-z]{5}
[*$()]

. ,
. * .
,
. , , , :
/[ A A-Z]/;

f ,
f

], * - , . "
. ] ,
/[\]]/. (-)
, .
Perl .
, . 6.3.

6.3.

, ( ), ,
[a-zA-Z0-9_]

\W

, , \w

\d

, , [0-9]

\D

\s

, , [ \ t \ f \r\n]

\S

100

I. Perl

:
/\d{5}/;
i
/\s\v+W; \ ,
t
! , , , .
, , ,
. don't -
. .


, . , , ,
dogs cats. ,
|, :
if(/dogs|cats/) {
print " \$_ \";
}

, ,
. frog, bog, log, flog
clog, /frog|bog|log|flog|clog/ .
. :
/f||1|f1|clog/;

* !

,
Perl , .
Perl
{).
/(fr|b|l|fl|cl)og/;
, , .
: / ( f r | b | l | ( f jc)l)og/.
, .
,
1. :
$_="apple is red";
($fruit, $color)=/(.*)\sis\s(.*)/j

( ), , is,
, (
). , , $fruit $color,
.

6- .

101


( , : " ?!") . ,
( ) .

' ( ). ^
, , . , /"video/ video,
.
($). , , ,
. , /earth$/ earth, . (. 6.4).

6.4.

/"Help/

, Help

/"Frankly. *darn$/ , Frankly darn. ,


/*hysteria$/
/" $ /
1

, hysteria

. /$/

.
. sill, .
:
&I 6_! _1;
,
$_, _. 0, .
:
$_="Our house is in the middle of our street";
s/middle/end/;
$ : Our house is in the end of our street
s/in/at/;
t : Our house is at the end of our street
if (s/apartment/condo/) {
t , . .
}

, . middle
end, a in at. if , $_ apartment, .

102

I. Perl


-. s, :
ststreetiavenuel;

:
,
( ), . . 6.1
, .
6.1
Moon. , 1- , " Perl".
6.2.

6.1.
1: JM/usr/bin/perl -w
2:
3: print " :";

4: $_=<STDIN>;
;
5: s/A\s+//; *
6:
7: if (/(18?|?|?|?}/1) {
8:
if (/\8*(1?|?).*//1) {
9:
$_*=0.4536;
10:
} else~{
11:
/\8*{?1(?).*//;
12:
}
13:}
14:print " : ", $ *.16667, " \";

6.2. Moon
1:
2:
3:
4:
5:
6:

$ perl Moon


$ perl Moon

:4
: 0.66668
:6
: 0.453609072

| .
1. (
) -w.
!

6- .

103

34. , chomp
$_. ,
, chomp $_.

5. /*\s+/ .
, .

7.
.

89. s/\s*(lbs? |?) .*//i lbs


(
). , ( , ) lbs . $_ 0.4536 .

. $_
, .

14. , $_, 1/6 .



, $_, . . $_,
, , Perl, .



$_, .
$ . -,
, - $_
.
$_ , Perl . Perl $_ - , , . 8- , "", .
, 6.1, $weight.
"" . =":
$veight="185 lbs";

$weight=~/ lbs//; f $weight


104

I. Perl

=" , ,
. ,
$_, :
$poem="One fish, two fish, red fish";
$n=$poem="m/fish/; $ $n ,
$ fish


. , .
, :
/[Mm][Aa][Cc]tBbJ[Ee]tTt][Hh}/;
, , -
. .
(s///) (//) ,
. i, :
/macbeth/i;
Macbeth , -
(MaCbEtti).
i, , . ( )
:
, .
g , , :
$_="One fish, two frog, red fred, blue foul";
F=m/\H{f\w\w\w)/g;
- ( ), f
. f . F
: fish, frog, fred foul.

.
, . :
$letters=0;
$phrase="Hhat's my line?";
vhile{$phrase=~/\w/g> {
$letters++;
}
(//) g ,
while.
. while ( $letter ) , .
$letters 11.

- .

105


9- , " ".


Perl , ,
, $1
( ), 2 (), $3, $4 .. :
/(\d<3>H\d{3>H\d<4))/
, , 800-555-1212.
$1, $2 $3.
, :
if (/(\d{3>)-(\d{3>)-(\d{4>)/)
{
print * $1";
}
, $1, $2 ..
, :

s/(\d{3})-(\d{3})-(\d{4})/Kofl $1, $2-$3/;


,
, . ,
, . , :
m/(\d{3})-(\d{3})-(\d{4})/;

print " $1";


t ,
$
$1
. .

:

Perl. , ,
. Perl
. :
,


.
$_. ,
. :
8dogs=qw(greyhound bloodhound terrier mutt chihuahua);

t!hounds=grep /hound/, dogs;

106

I. Perl

?dogs $_, /hound/. , , grep


dhounds.
. , $
$_
, :
Ghounds=grep s/hound/hounds/, Gdogs;
^hounds greyhounds
bloodhounds ( s ). Gdogs
- $_. greyhounds, bloodhounds, terrier, mutt chihuahua.
, , ,
grep . . , :
eiongdogs^grep length{$_)>8, Gdogs;
grep UNIX,
. , UNIX.
"grep- " .
grep . , ,
$_.
, :
f!words=map {split ' ', $_} Ginput;
ginput, $_, split. -
. , dinput
, Swords.

, ,
Perl. . , , , ( ). .


/\W(\w)+\W/ ,
, ?
, -. , , -.

6- .

107

// //? .
, . m
- , /, , ,
!
, , /\d*/ .
!
* , , 2 , 100, 1000 .
, /\d+/.

- , .


1. =,
?
a) s/{.+)=(.+)/$2=$l/;
)/(*)-(*)/$2-$1/;
) s / ( . * ) = ( * ) / $ 2 $ 1 / ;

2. $2 ?
$foo="Star Wars: The Phantom ";
$foo="7star\s((Wars): The Phantom Menace)/;
) $2 , ;
) Wars;
) Wars: The Phantom Menace.
3. / [-+]?[0-9] + (\.[0-9]*)?$/? "
) , --;
) , 45, 15.3 -0.61;
) : 4+12 89+2.

1. ). )
. ) *
- . ) .
2. ). , star , L , ,
$1, $2 , .

108

I. Perl

i star
, ).
3. ). + - ,
, . .

,
. , , :
12:00am, 5! 00pm, 8:30. 3:00, 2:60am, 99:00am, 3:0pm.

, .

1. .
2. .
3. .
4.
, thoughts yardstick.

6- .

109

7-

Peri. , , .
, .
,
.
. ,
. , , , . . , , . -.
.
,
,
. :
, , ..
,
-. - : , , , , -, ,
.
Perl , , . , .
. , Perl
10, 100 000 . , ..
. .
Perl . , .
Perl ,
.

110

!. Perl

- Perl (%). . , %,
8 $. .
.
. .


,
. :
SAuthors{'Dune'}='Frank Herbert';
Uuthors. Dune, Frank Herbert.
Dune Frank Herbert. $Authors{'Dune'} , : , , . ,
, .
$Authors{}, %Authors{}?
, , , , . ($),
, ,
. Perl $Authors{'Dune'} , Frank Herbert.
, , .

, :
$food{'apple'}='fruit';
$food{'pear'}='fruit';
$food{'carrot'}='vegetable';
, . , :
%food=('apple',

' f r u i t ' , 'pear',

'fruit',

'carrot',

'vegetable');

, 4- , " : ". ,
.
, ,
. Perl - =>.
, Perl,
:
%food=( 'apple' => ' f r u i t ' ,
'pear' => ' f r u i t ' ,
' c a r r o t ' => 'vegetable'.

7- .

111

Perl, , . , => , . , ,
. :
$Books{Dune}='Frank Herbert';
%food=( apple => ' f r u i t ' , pear => ' f r u i t ' , carrot => 'vegetable' );
- ,
( ) .


$,
, :
%Hovies= ( 'The Shining' => 'Kubrick',
'Ten Commandments' -> 'DeMille',
Goonies => 'Spielberg');
print $Hovies{'The Shining'};
The Shining IMovies.
Kubrick.
.
, . , ,
.
keys.
, keys . ' :
foreach $film (keys IHovies) {
print "$film\n";
}
$film , keys %Movies. , :
foreach $film (keys IMovies) {
print " $film $Movies{$film}.\n";
}

:
Ten Commandments DeMille.
The Shining Kubrick.
Goonies Spielberg.
$film , $Hovies{$film}
.
. ,

112

I. Perl

, keys .
keys, Perl values, .
, . values , keys . :
0Directors=values %Hovies;
GFilms=keys %Movies;
^Directors GFilrns fcMovies. $Directors[0] $Films[0] ..
, . , .
, , .. , :
%Movies= ( 'The Shining' => 'Kubrick',
'Ten Commandments' => 'DeMille',
Goonies => ' S p i e l b e r g ' ) ;
%ByDirector=reverse IMovies;

? reverse :
( 'The Shining', 'Kubrick',
'Ten Commandments', 'DeMille',
'Goonies', 'Spielberg' )
, :
( 'Spielberg', 'Goonies',
'DeMille' , 'Ten Commandments',
'Kubrick', 'The Shining' )
, - . %ByDirector
, , , , .
, . , , ,
, .
, .



. , Perl
. ,
:
%Movies= ( 'The Shining1 => 'Kubrick',
'Ten Commandments' => 'DeMille',
Goonies => 'Spielberg');
CData=%Movies;

7-.

113

@Data .
( ) , .
, , %Movies:
%Movies=GData;
Perl ,
.
. (.
" "), ,
(. " " ).
.
:
%New_Hash=%Old_Hashj
%Old_Hash , ,
Perl , Perl , %New__Hash. , :
%Both=(%First, %Second);
IAdditional=(%Both, keyl => 'valuer, key2 => (value2')J
, %First %Second %Both.
%First %Second, -
- . %Both
-. -. %Additional.


Perl,
. -
,
.


, , ,
:

if ( $Hash{keyval} ) { t
, ,
keyval , ,
keyval. :

if { defined $Hash{keyval} ) { i

114

!. Perl

, . , keyval, . undef:
$Hash{keyval}=undef;
,
, . ,
? Perl exists. exists (
), ( ):
if { exists $Hash{Jceyval} )

$ !


. ,
undef .
delete:
delete $Haeh{keyval};

:
Hash=();


Perl , .
.
. -
.


6- , " ", ,
. :
while(<>) {

while { /(\w[\w-]*)/g ) { t
$1.
$Words{$l}++;
. . $_. while , $_. 6- , "
", , (//) g
, .

7- .

115

\w, (
) [\w-]*. $1, .
. $1
,
. %Words.
- . , , 1.
,
1, .. 2. ,
.
%Words
. ,
:
foreach( keys %Words) {
print '$_ $Words{$_}\n";



, . ,
, . ,
. .
, :
dfishvGrds={'one', 'fish', 'two', 'fish', 'red', 'fish', 'blue', 'fish');
, 7.1.

7.1.
1:
2:
3:
4:
5:

%seen={);
foreach(f!fishwords) {
$seen{$_}=l;
}
Guniquewords=keys %seen;

.
I. %seen, .
2. ,
$_ .
3. %seen, $ , 1.

116

I, Pert

5.
@uniquewords. , fish,
, .


(.. ) (.. ,
). , . , . :
Gstars=('R. Reagan', '. Eastwood', 'M. J a c k s o n ' , ' C h e r ' , ' S . B o n o ' ) ;
epols = ('N. G i n g r i c h ' , ' S . Thurmon', 'R. Reagan',
' S . Bono', 'C. Eastwood', 'M. T h a t c h e r ' ) ;
7.2.

7.2.
1: lseen=();
2: foreach (Gstars) {
3:
$seen{_}=l;
4: }
5: Gintersection=grep($seen{$ }, Gpols);
'. .
1. %seen,
.

2. $_.

3. ,%5
1, .

5. , .
grep Gpols,
$_. %seen. ,
. , $_
^intersection. , grep gpols.
^intersection ,
Gstars, @pols.

, .. ,
, 7.3.

7- .

117

7.3.
1: %seen={};
2: foreach {(!stars} {
3:
$seen{$ }=1;
4: }

5: edifference=grep{! $seen{$_}, ipols);


. - %seen, grep
, , .
, %seen, difference.
, ,
, @stars Opols.


, ,
. ,
. keys ,
sort :
foreach ( sort keys %Words ) {
print "$_ $Words{$J\n";
}

. 4- , " : ", sort ASCII.


, sort , . :
foreach ( sort { $Words{$a} <=> $Words{$b} } keys %Words ) {
print "$ $Words{$_}\n";
}
, sort , $ $ , sort. $ $ %Words. $ $ %Words,
.

: Perl

, , , ,
, ,
- , . , ,
. , Perl?

118

). Perl

. ,
, .
.
, .
,
customers.txt. , . .
Smith,John (248)-555-9430 jsmitheaol.com
Hunter,Apryl (810)-555-3029 aprilishowers.org
Stewart,Pat (405}-555-8710 patsistarfleet.co.uk
Ching,Iris (305)-555-0919 iching8zen.org
Doe,John
(212)-555-0912 jdoeimorgue.com
Jones,Tom
(312)-555-3321 tj2342iaol.com
Smith,John
(607)-555-0023 smithipocahontas.cojn
Crosby,Dave (405)-555-1516 croscsny.org
Johns,Pan
(313J-555-6790 pjisleepy.com
Jeter,Linda (810)-555-8761 netlessiearthlink.net
Garland,Judy (305)-555-1231 ozgalirainbow.com
, 7.4,
Customer. He , , 1- , " Perl".
,
perl Customer
7.5 Customer. ,

7.4. Customer
1: j!/usr/bin/perl -w
2:

3: open(PH, "customers.txt") or die " customers.txt: $I\n";


4: while(<PH>) {
5:
chomp;
6:
{$number, $email)=(split(/\s+/, $_))[!,2J;
7:
$Email{$email}=$_;
8:
$Phone{$number}=$_;
9: }
10:close(PH);
11:
12.-print " 'q'\n";
13:while (1) {
14:
print "\? ";
15:
$number=<STDIN>; chomp($number);
16:
$address="";
17:
if (! $nunber ) {
18:
print "E-Mail? ";
19:
$address=<STDIN>; chomp(Saddress);
20:
>
21:
22:
next if {! $number and ! $address);
23:
last if ($number eq 'q' or $address eq 'q'>;

7-.

119

24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:}

if ( $number and exists $Phone{$number} ) {


print ": $Phone{$number}\n";
next;
}
if ($address and exists $Email{$address} } {
print ": $Email{$address}\n"
next;
}
print " .\";
next;

37:print " .\n";

7.5. Customer
1:
2:
3:
4:
5:
6:
7:

8:

' q '
? <Enter>
E-Mail? cros@csny.org
: Crosby, Dave
(405)-555-1516
? (305J-555-0919
: Ching, I r i s

crosdcsny.org

{305)-555-0919 iching@zen.org

9: ? q
10:

11: .
.

I. (
) -w.
!

3. customers.txt .
, .

4S. (
$_). ,
$_, chomp.

6. , $_, /\s+/,
. split
.
, ,
split, $number Semail .

120

I. Perl

7-8.
: %Email %Phone. , .

10. .

13. while, .
while (1) Perl .
last.

1415.
.
1720. ,
.
2223. , . q, .
2528. , 26
. next.
3033. , .
next.
Perl.
. Perl , , . ,
,
while, do, until
.

Perl .
, . ,
. , DBM-, , .


, .. ,
?

. . ( ) ,
, . '
join, split.
.

7- .

121

.
, .
, . 13- , " ".
, ?

. ,
.
.
push. , , keys. .
Tie: :IxHash, keys , . 14- , " ".
?

. Data:: Dumper Storable , .


.
15- , " Perl"
DBM-. DBM-
.
. ,
.


1. Customer
?
) Perl , ;
) ;
) .
2. ?
) ;
) , ;
) Perl ,
.
3. ?
) ;
) ;
) -.

122

I. Perl


1. ). Perl ,
. ,
. , John Smith Robert Jones.
2. ).
. , .
3. ),
, .

Customer , .
,
.

Customer ,
(,
). ,
. ,
.

7- .

123

8-

.
, .
print, reverse, sort, open, close, split .
Perl.
Perl . Perl .
, .
Perl . , .
, . .
.

use strict .


Perl :
sub _ {
1;
)
>
, , . 2- , "
Perl: ". .

124

!. Perl

,
Perl. , ,
.

, . , :
sub yesno {

print " (/)?";


$answer=<STDIB>;
}
, , , :
&yesno{);

yesnof);
( &) , , &yesno( ) . S, .
Perl , , :
sub countdown {
for($i=10; $i>=0; $i~) {
print "$i -";

}
print " : ";
countdown{);
print "!";
Perl
:
sub world {
print "World!";
}

sub hello {
print "Hello, ";
world();
)
hello();



. , , Perl,
. .

, return.

8- .

125

, . :

sub twb_by_four { #
2*4;
print 8*two_by_four();
Perl 8*two__by four{)
two_byJ:ourO, 8. 8*8
64.
return.
. :
subx_greaterthanlOO {
f $
return (I) if ($x>100);
0;

$=70;
if (x_greaterthanlOO()) {
print "$x is greater than 100\n";
, :
sub shift_tojippercase {
Gwords=qw( cia fbi un nato unicef );
foreach (ewords) {
$_=uc($J;
return{words)j
eacronyms=shift_to__uppercase( J

, , , (2*4), ($
x_greaterthanlO0). .
: " ", :
" ".
.
, , ( ). ,
Perl (grep, sort, reverse, print .) . . :
_{1, 2, );
_ aprl, 2, ;
& _ (aprl, 2, );

126

I. Perl

, Perl .

@_. , .
sub printargs {
print join(\\ 0J;
}

printargs ('market', 'home', 'roast b e e f ) ;



(!_, . ,
_[0] $_.
sub print thirdargument {
print~$_[2];
}

$_[3]
. , ,
, ~
, . , :
sub display_box_score {
($hits, $at_bats)=_;

print " $at_bats $hits .";


print " ~ ", $hits/$at bats, "\n";
}
display_box_score(50, 210);
@_ ($hits, $at_bats).
0_ @_[0] ?hits, $at_bats.
.
3_ .
.
,
, .


. , .
, :
sorted_itens=sort_numerically(eitems);
?items 0_:
sub sortjiumerically {
print "...";
return(sort {$a <=> $b} 3 );

8- .

127

,
. :
sub display_arrays {

(, )=_;

print " : \";


print " : \";

}
dispay_arrays(first, isecond);
Sfirst ^second
@_.
. (, @)=@_ , ,
. , , 4- , " : ".

.
. ,
:
sub lots_of_args {

($first, $second, $third, ?)=_;


# ...

}
lots_of_args($foo, $bar, $baz, (jmyarray);
, , . , , 13- , " ".


, ,
. , .
,
.
, ,
, . " ", . .
.
t
sub moonweight {
{$weight)=e_;
return ($weight/6);
}
print moonweight(150);
.

128

I. Perl

sub moonveight {
return($weight/6);
}
$weight=150;
print moonweight;
, . .
$veight .
, , Sweight
, . , , moonweight (), .
, , - - . $weight , .
Perl . Perl
. .
, , . :
sub moonweight {

$weight;
($weightH ;
return($weight/l.66667);

}
moonweight () $weight .
. ,
$weight $weight
moonweightf). .
, , .
, ,
. , Perl ( $ ! , $ , 8_ .) .
, :

my ($larry, curly, %};


, .
, , :
sub myfunc {
my $x;

$=20; \ $
print "$\";

)
$=10; i $
print "$x\n";
myfunc();
print "$x\n";

8- .

129

10, 20,
10. $ myfunc() $ . : " ,
?" , , Perl.
, Per! @_ :
sub playerstats {

my ($at_bats, $hits, $walks) =_;


* ...
}
,
, , :
, , .
.


,
. .
, - . :
$=20;
{
$=500;
print ' \$ $\";
500
)
print$\"; # 20
, for,
foreach, while if. , , , :
while($testval) {
my $stuff;
}

foreach(et) {
my %hash;
jf foreach
}
, ,
.
Perl 5.004 () for foreach, a
while if :
foreach my Selement (Garray) {

t $element fpreach()

130

I. Perl

whilefmy $line=<STDIN>) {
i $line while()
}
.

:
, .
. .
. ,
, .
, .
.
. , , , , ,
68% , ,
95% .
, , , 8.1, Stats. He
, 1- , " Perl".
,
perl Stats
8.2 .

8.1. stats
1: jM/usr/bin/perl -w
2:
3: use strict;
4: sub mean {
5:
ny{Gdata>=_;
6:
my $sum;
7:
foreach(edata) {
8:
$sum+=$_;
9:
)
10:
return{$sum/f!data);
11: }
12: sub median {
13:
my(?data)=sort { $a <=> $b} (
!
_
;
14:
if (scalar{edata)%2) {
15:
return($data[gdata/2]);
16:
} else {
17:
my($upper, $lower);
18:
$lower=$data[gdata/2];
19:
$upper=$data[Sdata/2 - 1J;
20:
return(mean{$lower, $upper)};

8-.

131

21:

22: }
23: sub std_dev {
24:
my{Hata)=e_; .
25:
my($sq_dev_sua, $avg)=(O,O);
26:
27:
$avg=Etean(edata);
28:
foreach my $elem (ddata) {
29:
$sq_dev_sum+=($avg-$elem)**2;
30:
}
31:
return{sqrt($sq_dev_sum/(fidata-l)));
32: }
33: my($data, ddataset);
34: print " , : ";
35: $data=<STDIN>; chomp $data;
36: edataset=split(/[\s,]+/, $data);
37:
38: print ": ", median(Sdataset}, "\n";
39: print ": ", mean(idataset), "\n";
40: print ". .: ", std_dev{f!dataset), "\n";

8.2. Stats
, : 14.5,6,8,9,10,34
: 9.5
: 13.5833333333333
. .: 10.3943093405318
.
1. (
) -w.
!
3. use strict ,

.
411. mean{) . foreach $sum,
.
1221. median() .

. 2,
.
.
$upper $lower. mean(). .

132

I. Perl

2332. stddevf) .
data
.
$sq_dev_sum. ,
.
3335. . , Sdata. split
/[\s,]+/ Odataset. . .
3840. . ,
, mean(), medianf) std_dev().
: std_dev() median{}
mean(). .


, , , , . use
strict, Perl, .


l o c a l
Perl 4 - .
Perl 4 "" . "" Perl 5. . local:
sub myfunc {
local {$foo)=56;

* ...
>
$foo myfuncf).
, local, , . , eval.
.
, , ,
, , , . . 8.1 .

8- .

133

8.1.
sub mess_with_foo {
submess_with_foo
$foo=0;
$foo=0;
}
>
sub myfun {
my $foo=20;
mess_with_foo(
print $foo;

sub myfunc {
' local $foo=20;
mess_with_foo();
print $foo;

myfunc{);

myfunc();

, . 8.1, , $foo myfuncf). , .


mess_with_foo() $foo. myfunc{) 20,
$foo, , .
mess_with_foo() $foo. mess_with foo(} $foo 0.
, myfunc(), ~- . myfunc() 0.
,
,
. ,
, ,
. , , s .
, - , ray.

Perl
Perl .
, , . Perl, . , , , . Perl
, .
(
) , Perl -
. -w, Perl
. use strict:
use strict;
sub musub {
my $x;
mysub{);

134

I. Perl

use s t r i c t .
Perl, .
, ,
.
( 6 ) ,
.

use s t r i c t .
. ,
.
, use strict, .
$var=value;
, value . use strict Perl ,
,
.
use strict.

.
. .
, , , ,
, ..
: , .. ,
.
. . ABCDEF . , , 1. , 6 6x5x4x3x2x1 720. 6 5 6. 5 4 5 .. 8.3.

8.3.
1: sub factorial {
2:
my ($num)=g_;
3:
return(l) if {$num <= 1);
4:
return($num*factorial($num-l));
5: }
6: print factorial(6);

8- .

135

! .

2. factorial!)
$, .

3. . ,
. factorial () 1 0. , factorial(), 0
1, return(l) ( $<=1).

4. , , .

$num ... 8 4 ...

5
4
3
2

return(6*factorial(5))
return(5*factorial(4))
return(4 *factorial{3))
return(3*factorial(3)}
return(2*factorial(l))

4 ; f a c t o r i a l ( l ) 1

, . , 6.
. . , for, while,
foreach, , , ,
.
, .

Perl , , .
; . Perl .
Perl
, .


- & ?

, - .
sfoo foo

136

I. Perl

. .
, perlsub

my($var), Perl
syntax error, next 2 tokens (.
- , Perl 4.
perl -v. ,
.
, ,
?
, , 13- , " ".
10:: Handle (typeglob). .
, .
?
,
.
. ( 1900)
localtime, :

print " ", 1900+ (localtime)[5J;


, undef - :
(undef, undef, undef, undef, undef, $year offset)=localtime;


:
sub bar {
<$, $)=_;
$=100;
$=$+1;
}
sub foo {
my ($a)=67;
local($b)=e_;
($, $);
}
foo(5, 10)
1. $
bar($a, $b)?
) 5;
) 100;
) 68.

8- .

137

2. foo()?
) 67;
6)68;
) undef.
3. $ foo{)?
) ;
) ;
) .

1. ). $
foo{), (
local ).
bar () $ 100.
2. ). ? foo() bar($a,$b) 68, $
{) . foo()
68.
3. ). , local, .

, ,
, 7- , "",
. , .
.
,
. 0, 1, I, 2, 3, 5, 8. ( 0 1). .

138

I. Perl

II
Perl

9

140

10

154

11

172

12

Perl

187

13

200

14

216

15

Perl

230

16

Perl

249

9-


Perl : "
-". .
" " .

. Perl
-, . ,
.
, ,
foreach, join.
.
, , "" print
.
print , .
.

print.
.


,
. Perl " " (, ) ,

140

II. Perl

. ,
. Perl
.

index
,
Peri index.
:
index ,
index , , _
index .
index , , 0 . , index
-1. ,
, . , .
. , Perl
, .

index " ", ""; f 16


index(" - , - ", ""); f 29
$=" - ";
index($a, ""); I 8
index($a, ""); I -1
=(1 );
index join(' ", ), ""; f 8
( ) index , ,
. ( ), 0.

$nanes="repu ";
index($names, "") ;1 0
index{$names, ",1);1 5
index , ""
,
:
$source=Tepq ";
$start=0;

f "",
I $start
. $start

while(($start=index($source,"",Sstart)) 1=-1){
print " $start-fi \";
$start++;
}
:
0-
5-

9- .

141

12-
24-

<

index
$source, :
$start

index 0- ,
Sstart
index 1- (Sstart+1)

index 5-


rindex
rindex , index, ,
. .
rindex ,
rindex , , _
, , rindex -1. .

$'= " , ...";


rindex($a, ""); \ 31
rindex($, "", 30); I 1
index,
rindex . ,
rindex . , . , length($source), .
rindex -1. $start 1,
, index.

$=" ";
$start=length($source);
while(($start=rindex{$source,"",$start)) !=-l){
print " $start-i ";
Sstart;}

142

II. Pert


substr
substr , , . :
substr ,
substr , ,
substr , , ,
(.. ).
, .
, . .
# $
f
0
10
20
30
40
50
$="0 ";
p r i n t substr($a, 50);# ""
p r i n t substr($a, 10, 12);# " "
, substr . , substr($a, -5)
$. , substr
, , . :
p r i n t substr{$a, 30, -4};f " "
substr 30-
4- .
substr . , . substr , , . substr,
$=" , ";

# "" ""
substr($a, 4, 4)="";
# ":"
substr{$a, 0, 0)=":";
# 4
substr{$a, -4, 4)="";

,
( ), , , , 6- , " ".

9- .

143

/// , =",
, $_.
- , , .
:
t / _ / _ /
tr/// ,
, .
, $_.
, =",
, :

tr/ABC/XYZ/; # $_ "" "X",


"" "Y" ..
$r=~tr/ABC/XYZ/; # $
. , A-Z Z .
, :

tr/A-Z/a-z/;
f
tr/A-Za-z/a-zA-Z/; #
, tr/// . , :
$eyes=$potato="tr/i//;
$nums=tr/0-9//;

"i"
$potato
$eyes

$_
$nums

, tr/// ///.
, tr .
tr/// ( , ///) .

, :

tr(a-zHn-za-m); f 13
f $_.
[,._-][;:=|]
I
tr/// , . , prelop .


,
print, . , print ,

144

II. Perl

.
Perl printf.
, , ,
. printf , , (, print using
BASIC). printf :
printf _,
printf _ 6_,
6_
. ,
printf ( , print).
( STDOUT), ,
print, ,
. , .
(
) . , , , %, . , %-w.dx (. 9.1). (/ ; d ( ) ; . w , w . . .
. 9.1.

""
()
1

-v.dx

()

" "

. 9.1.

9.1.

9- .

145

- Perl. perldoc -f printf.


printf.
jrintf("*20s", '"); # "",
t 20 .
t
printf("%-20s", ""); # ,
i
Samt=7.12;
printf(46.2f", $amt); * " 7.12"
$amt=7.127;
printf{"%6.2-f", $amt); f " 7.13",
printf("%c", 65);
ASCII-,
# 65 ("")
$amt=9.4;
printf<"%6.2f", $amt);
I " 9.40"
priatf("%6d\ $amt);
* "
9"
, . 9.2.
, ,
.

printf(": %6.2f %15 I7.2f ", $a 5b $c $d};


. 9.2.
, 0 , :

printf{"%06.2f", $amt); * "009.40"


printf, sprintf.
, sprintf , .
, :
$weight=85;

t 2-
$moonweight=sprintf("4.2f, $weight*.17);
print " $moonveight .";
, printf sprintf,
%f,
, .

:
, , . ,
. .

146

II. Perl

, ,
. . , , , .
, : ,
, .
.
,
. ,
. ,
, .
.
, , ,
9.1, Employee. . , 1- , " Perl".
,
perl Employee
9.2.

9.1. Employee
1: #l/usr/bin/perl
2:
3: use strict;
4:
5: my employees=(
6:
',,123101,9.35,40',
7:
',,132912,10.15,35',
8:
',,198131,6.50,39',
9:
'Her,;141512,9.50,40',
10:
',,131211,11.25,40',
11: );
12:
13: sub print_emp {
14:
my {$last,$first,$erap,$hourly,$time)=
15:
split(',',SjOJ);
16:
my $fullname;
17:
$fullname=sprintf("%s %s", $first, $last);
18:

printf(-%6d %-20s %6.2f 13d %7.2f\n",

19:
$emp, $fullname, $hourly, $time,
20:
{Shourly * $time>+.005);
21: }
22:
23: gemployees=sort {
24:
my ($L1, $Fl)=split(\', $a);
25:
my ($L2, $F2)=split(',', $b);
26:
return ( $Ll cmp $L2 \
27:
||
$ ...

9- .

147

$F1 $F2 I
28:
29:
} ^employees;
30:
31:
32: foreach(0employees)
33:
print emp($ );
34: >
9.2. Employee
1: 198131
2: 131211
3: 141512 Her
4: 123101
5: 132912

6.50
11.25
9.50
9.35
10.15

39
40
40
40
35

253.50
450.00
380.00
374.00
355.25

; .
7. (
) -w.
!
3. use strict ,

.
5-11. ^employees. :
, ,
.
2330. ^employees , .
24. ($) . $, $F1.
.
25. ($). $L2, $F2.
26~29. . sort 4- , " :
".
3234.
^employees. print_emp().
1321. print_emp()
.

148

II. Perl

1415. print_emp() $_[0]. ,


$last, $first .., printemp ().
17. sprintf. .

18-20. . (
$tiroe) (
$hourly).
.005.


,
(. 9.3).
0

. 9.3.

(. 9.4).
.
,
. .
. . (.. ). ,
.
Perl .
push,
pop. ,
. shift
unshift . . 9.5.
:
pop
shift
unshift , _
push , _
pop shift .
, 0_, GARGV. pop
shift ,
, undef.
.

9- .

149

Pop

Push

. 9.4.

Unshift

Shift
. 9.5.

pop, shift, unshift push @_, .


IARGV, .
push unshift _ . . _
, ,
.
band=qw(TpoK6oH);
push 8band, qw( );
gband :
# "", "", ""
$brass=shift 8band; I $brass ""
$wind=pop gband;
$wind "" \ 'gband - ''
unshift ?band, "";
\ ?band :
t "" ""
push,
pop, shift unshift ,
.
,

push @list,8newitems
,

eiist=(81ist,8newitems). Perl .
150

II. Perl

, , . ( ) 0, .


,
, , . splice,
, . :

splice ,
splice , ,
splice , , ,
splice , .
.
, ,
. ,
. , .
. :

veg=qw(MopKOBb );
splice (veg, 0, 1);

0veg
: ""
splice {8veg, 0, 0, qw(ropox));
veg
: "", ""
splice (veg, -I, 1, *(, )); # Bveg
: "", "", ""
l!veg
splice (t!veg, 1, 1);
: "", ""

, ;
index rindex. ,
tr///. , substr. ,
printf sprintf.
() .


substr, index rindex? , ?

-,
. index rindex -

9 .

151

. -, ;
substr. , ,
-, Perl ,
. ,
.
, substr ( index,
rindex) , ?
,
. " ,
...?", , .
, , use of undefined
value ( ,
!). . ,
$a="Foo"; substr($a,5); substr undef.


1. @
?
=<( );
s h i f t ;
push , "";
Pop

) ;
) ;
) .
2. printf("%18.3f",$a)?
) , 18 (15 3 );
) , 18 3 ;
) , 18 (14 3 ).
3. , tr/a-z/A-Z/.
tr/A-Z/a-z/?
) ;
) , .

152

II. Perl


1. ). shift
"", push "". pop . ,
_, @.
2. ). ),
,
18 (18=14+1+3).
3. ). , "Rosebud" tr/a-z/A-Z/ "ROSEBUD".
tr/A-Z/a-z/ "rosebud",
, .

Hangman, 4- ,
" : ", ,
.
substr.
, 9.1, ,
.
, ,
. .
.

9- .

153

10-

. , , .
, , . () .
.
,
() . , , , , , , .. .
Macintosh,
( , ),
.
Perl , .
Perl , UNIX, , . ,
Perl . , , Perl ( ,
).
.

.
.

154

II. Perl


, .
,
, . opendir:
opendir _, ^;
_ ,
, _ ,
. -
(, , ), opendir false.
,
( 2- , "
Perl: "). , Perl,
. opendir:

opendir(TEMPDIR, '/tmp') {{ die " /tmp: $!";


(/), UNIX. ,
( Perl \) Windows.

readdir:

:
readdir ;

,'"'.,.

readdir undef, .
readdir . ,
, , ,
UNIX . . , . , readdir
: . . . , . .

closedir:
closedir ',
:
opendir(TEMPDIR, '/tmp'} ||

die " /tmp: $!";


FILES=readdir TEMPDIR;
closedir(TEMPDIR);

10- .

155

FILES. , ,
, . . . . ,
. :
eFILES=grep(!/ A \.\.?$/, readdir TEHPDIR);

/ \.\.?$/ , . grep , .
, , :
FILES=grep(/\.txt$/i, readdir TEMPDIR);
, readdir, ,
opendir . ,
, :
opendir(TEMPDIR, '/tmp') ||

die " /tmp: $1";


while($file=readdir TEMPDIR) {
# !I!
open{FILEH, $file) ||
die " $file: $!\";
}
closedir{TEHPDIR);
, /tmp, open(FILEH, $file) .
, /tmp, open . ,
/tmp /tmp , open
. open
. :
opendir(TEMPDIR, '/tmp') ||
die " /tmp: $1";
while($file=readdir TEMPDIR) {
!
open(FILEH, "/tmp/Sfile") j|
die " $file: $!\n";
}
closedir(TEMPDIR);


,
(globbing). DOS,
dir *.txt. dir ,

156

II. Perl

*.txt. UNIX ,
. ,
dir UNIX : Is *.txt. , .txt.
Perl glob,
. :
glob
, . , . ,
, . 10.1. glob , .
, .
glob . ,
.

10.1. glob

...

f?d fud,
fid, fdd ..

f*d fd,
fdd, food, filled ..

[]

, f [ou]d fod
. fud, fad
MacPerl

{}

, - f*.{txt,doc} . , f MacPerl
. t x t .doc
UNIX. Perl glob , .
, Bourne ( ).
UNIX, Perl,
, . , ,
* ?. .

.
# .h /usr/include
my f!hfiles=glob{'/usr/include/*.h'};
\ ,
# 1999
my Scurfiles=glob{'*1999*.{txt,doc}'};

10- .

157

f
$count=lj
while($name=glob('*')) {
print "Scount. $name\n";
$count++;
}
glob opendir/readdir/closedir.
glob .
, ,
, . ,
Perl glob
,
. opendir/readdir/closedir
.
glob , , opendir/readdir/closedir
. , glob( '/usr/include/*.h') /usr/include/.
glob , opendir/readdir/closedir. . Perl ,
, .
, , ? , . ,
opendir/readdir/closedir
.
opendir/readdir/closedir.
. ( ) ; glob, :
8cfiles=<*.c>; i ,
t .
,
, . glob.

:
UNIX grep
, . Unix grep.
, ( Perl).
. .

158

II. Perl

, , 10.1, mygrep. He ,
1- , " Perl". ,
Perl grep ( UNIX
grep).
,
:
perl mygrep

10.1. mygrep
1: f!/usr/bin/perl
2:
3: use strict;
4:
5: print " : ";
6: my $dir=<STDIN>; chomp $dir;
7: print " : ";
: my $pat=<STDIN>; chomp $pat;
9:
10: my ($file);
11:
12: opendirfDH, $dir) || die " $dir: $!";
13: while($file=readdir DH) {
14: next if (-d "$dir/$file");
15: if (1 open(F, "$dir/$file")) {
16:
17:
18:
19:
20:
21:

22:

warn " $file: $!";


next

}
while(<F>){
if (/$pat/J {
print "$file: $_"

23:
}
24:
close(F);
25: }
26: closedir(DB);

....-.-:.,
,

. ,

: .
1. (
) -W-
!
3. use s t r i c t ,

.
, . _.
5-8. $dir
( ) Spat ( ).
chomp.

10- .

159

10. use strict,


Sfile,
.

12. , $dir.
,
.

13. $.

14. ,
( -d), . ,
($dir/$file), $dir. , "$dir/$file".

15~18. , . ,
.
1923. , $pat. .
10.2.

10.2. mygrep
: .
: perl
hello: #!/usr/bin/perl
lstO2 01.pl: *!/usr/bin/perl -w

,
,

readdir. Perl ,
, , ( ).


- ""
, . UNIX
. , , UNIX pwd.
MS-DOS Windows
, C:\WINDOWS>. ,
MS-DOS cd ,
. , , , .

160

. Perl


Perl
, ,
, .
, Perl,
(
). Perl
, cwd.
, , , open(FH, "file") jj die,
. Perl chdir, :
chdir _
, .
, chdir false.
.
, , .
cbdir . UNIX ,
. Windows 9x, NT MS-DOS . , chdir .
Perl , . , . .
use Cwd, cwd,
:
use Cwd;

print " - ", cwd, "\n";


chdir '/tmp' or warn " /tmp: $!";
print " ", cwd, "\n";
use Cwd .
cwd , .
use Cwd Perl, Cwd. Perl , cwd. Can't locate Cwd.pm in ? INC
, , .
14- , " ".


Perl mkdir, :
mkdir , ',

10- .

161

, mkdir . , $!. _ UNIX, , ,


UNIX .
0755, , " UNIX".
DOS Windows 0755 ! , :
print " : ;
my $newdir=<STDIN>;
chomp $newdir;
mkdir($newdir, 0755) j| die " $newdir: $!";
rmdir, :
rmdir ;
, rmdir . ,
$!, :
print " : ";
my $baddir=<STDIN>;
chomp $baddir;
rmdir($baddir) || die " $baddir: $!";
rmdir . ,

.


Perl unlink, :
unlink _;
unlink , ,
. ,
, $_. :
unlink <*.bat>;
$erased=unlink 'old.exe', ' a . o u t ' , 'personal.txt';
unlink 8badfiles;
unlink; # , $_
, , , unlink, :
my Gfiles=<*.txt>;

$erased=unlink files;
f ,
\
if {$erased 1= files) {
print " : ",
', <*.txt>), "\n";

162

II. Perl

$erased.
unlink $erased ?files. . , , .
, unlink, , Perl .
!


Perl .
rename, :
rename _, ^;
, , , . , rename . , , . rename , , $!, :
if (! rename "myfile.txt", "arcfile.txt" ) {

warn " myfile.txt: $1";


}
rename .
, :
t
rename "myfile.txt", "/tmp/myfile.txt";
, , rename, , .
rename , .

UNIX
, Perl UNIX,
,
.
, .
, Perl UNIX. ,
UNIX. .
, , , unlink,
. UNIX,
UNIX. -

10- .

163

, , Perl , unlink ,
.
Perl , /.
, . Perl .
, Perl UNIX, ( UNIX) , ,
UNIX. UNIX, ,
.
,
UNIX
. ,
UNIX, "".
http://vwv.williamspublishing.com.


1- , " Perl", , , UNIX Perl , , ,
chmod 755 _. 755
, . , UNIX
chmod.
,
, , , (. 10.1).
7, 5, 5. . 10,2.

, 10.1.

10.2.

7

/ / , (RWX)

/ / (RW)

/ / (RX)

/ / (R)

164

II. Perl

. 10.2

/ / ()

/ / (W)

/ /
(X)"1

Perl
chmod, :
chmod _, _;
,
, , .
_ ,
.
chmod.
chmod 0755, 'file.pl'
chmod 0644, 'mydata.txt'
chmod 0777, 'script.pl'
chmod 0000, 'cia.dat'

RWX
RX

RH
R

RWX
( )

mkdir. , ( ,
chmod ). :
mkdir "/usr/tmp", 0777
mkdir "nyfiles", 0700

f
I
t
I

,

,

UNIX (mode). chmod change mode (


).
_ _ ^ _ _


Perl stat.
UNIX,
UNIX , stat . stat :

stat _;
stat ;
10- .

165

, stat ( ), .
stat , 13 , . , Perl. , . . 10.3 stat : UNIX Windows.

10.3. stat
UNIX

Windows

dev

( 2
:, 3 D: ..)

ino

(inode)

2
3

mode

nlink

(links)

0,
NTFS

uid

gid

(group id)

rdev

size

atime

mtime

10

ctime

11

blksz

12

blocks

(user id)



()



, . 10.3, , . ( UNIX),
.
stat:
f!stuff=stat

"myfile";

stat , , :
($dev, $ino, $mode, Snlink, $uid, $gid, $rdev, $size,
Satime, $mtime, $ctime, $blksize, $blocks)=stat(Hmyfile");

166

II. Perl

, , " ":
printf "t04o\n", $mode&0777;
.
, . , stat (
$mode), "" . &0777, "" , . , , 0777
. , , %04 printf
( 0 7), UNIX . 4 , 0 , .
, , 8. 0 7. 7 . , . UNIX, , , Perl.
, . printf
. ,
.
. 10.3 , .
, ( ). , . Perl , 0 1 1970 . , , localtime,
:
print scalar localtime($mtime);
, Mon May 15
14:44:55 2000. ( $atime) ,
, (
$mtime) . UNIX
$ctime ,
. , ,
.. , ,
, .
Windows $ctime .
,
stat. stat

, .
print " : ", ( s t a t f f i l e " ) ) [7], " ";

10- .

167

, , . , . , chapterJJl.rtf,
Chapter_02.rtf, Chapter_04.rtf .., Hour_01.rtf,
Hour 02.rtf, Hour_04.rtf ..
, Windows.
, 10.3, Renamer. ,
1- , " Perl".
,
:
perl Renamer
10.4 .

10.3. Renamer
1: #!/usr/bin/perl
2:
3: use strict;
4:
5: my($dir, $oldpat, $newpat);
6: print " : ";
7: chomp($dir=<STDIN>);
8: print " : ";
9: chomp{$oldpat=<STDIK>);
10: print " : ";
11: chomp($nevpat=<STDIN>);
12:
13: opendir(DBf $dir) || die " $dir: $!";
14: my eiiles=readdir DH;
15: close(DH);
16: my $oldname;
17: foreach(Hiles){
18:
$oldnajne=$_;
19:
s/$oldpat/$newpat/;
20:
next if {-e "$dir/$_");
21: if (1 rename "$dir/$oldname", "$dir/$_") {

22: warn " $oldname $_: $1";


23: } else {
24:
print " $oldname $_\";
25: >
26: }

163

II. Peri

S .

13-15. $dir files.

1719. Sfiles. $_, $oldname. 19


$_ .

20. , . .

2125. . -
, . ,
, $dir/$oldname. ,
Ofiles $_ .

10.4. Renamer
: tmp
: Chapter
: Hour
Chapter_4.rtf Hour 4.rtf
Chapter_2.rtf Hour_2.rtf
Chapter l.rtf Hour 1.rtf

^_

__

,
Perl rakdir, rmdir rename. , ,
(, .)
stat.
, , .


?
, .

opendirfDIRHANDLE, "/mydir") || die;


files=<DIRHANDLE>;
closedir(DIRHANDLE);
. DIRHANDLE , ! ( ) . ,
Gfiles=readdir DIRHANDLE.

10- .

169

g l o b e * . * " ) , ?
*.* , . ,
globf 1 *"). glob Perl , . *. *' MS-DOS.
opendir . - .
.
- . ,
. . , 15- , " Perl".
File::Find, ,
, .
, 10.3, *.bat *.tmp?
, *.bat, . - ,
. \*\.bat,
, ,
, "*.bat".
, , , .
, !9
:
s/\Q$oldpat/$newpat/;

, .


1.
foofile?
) print glob("foofile");
) print (stat("foofile"))[9];
) print scalar localtime (stat{"foofile"))[9].
2. unlink?
) ;
) ;
) , .

170

II. Perl


1. ) ). , 0 1 1970
, . .
2. ), )
. unlink
, 0, .

( .) , .

10- .

171

11-

Perl ,
: , , .
, .
,
.
Perl , (glue
language). , Perl
, ,
( ) . Perl ,
, , .
Perl
. , , .
,
. , .
.
system().

.
.
Windows DOS,
UNIX. , ,
( ) , .

172

. Per!

system ()
Pert system().
Perl, , Perl. system{) :
system ;

, . , system()
0.
- , . ,
" " true false,
Perl.
system() UNIX.

system("ls -IF"); #
system
if ( system("perldoc -f system") ) {
print " Perl i\n";
}
Windows:
system("dir /w"); f
< system
if ( systemfperldoc -f system") ) {
print " Perl !\";
}

, system!) .
,
. , DOS dir, UNIX Is. perldoc
DOS,
UNIX. .
system() , , Perl.
,
, Perl.

STDIN STDOUT Perl. , / . , system()
.
UNIX.
$file="myfile.txt";
system{"vi $ f i l e ' ) ;
Windows DOS :
$file="myfile.txt";
svstem("edit $file");

11- .

173

myfile.txt. UNIX vi, DOS edit. , , . Perl.


system() ,
( ) . , UNIX ,
, Perl:
system("xclock -update 1");
Notepad Windows, Perl:
system("notepad.exe myfile.txt");


system{), ,
, , . , system() (
UNIX /bin/sh, Windows DOS command,com), . , / (>), (|),
UNIX (&),
.
,
, Perl:
system{"perldoc perlfaqS > faqfile.txt");
perldoc perlfaqS faqfile.txt. , UNIX, DOS.
, , , .,
UNIX, DOS Windows .
:
I , $f,
i
system{"sort $f | lp"); t
1
I Xterm
system("xterm ");
xterm
Perl, (fi),
, xterm .
Perl .

174

II. Perl

UNIX systemf}, (
) Perl /bin/sh .
, . ,
UNIX.

system() Macintosh.
.
Macintosh Specific Features MacPerl.


, system(}
. Perl. ,
, .
I , ' d i r ' ' I s '
!
# opendir/readdir/closedir
system("dir > o u t f i l e " ) ; # UNIX ' d i r ' ' I s '
open(OF, "outfile"} || die " outfile: $1";
f!data=<OF>;
close(OF);
dir ( Is) outfile.
Sdata. , ,
dir.
. , Perl , .
Perl, ),
systemf).
, , :
$directory="dir~; # 8 UNIX ' d i r 1 ' I s '
, dir, $directory.
systemf),
: >
, | ( UNIX)
s . ,

Perl .
.
, -

11- .

175

.
. . :

f!dir=4dir*; # UNIX 'dir' 'Is'


foreach (Odir) {
#
}
foreach , gdir.
Perl .
qx{>. , , , :
$perldoc=qx{perldoc perl};
qx ,
,
, . (, .) .
$complex='sort \'grep -I 'conf * \ ' " ;

:
$complex=qx{ sort 'grep -1 'conf *'}; #
, , , () [ ].



Perl . .
UNIX:
$= * Is $HOHE';
DOS Windows:
$myhome=% dir %windir%";
, $?
Perl, ?
? Swindirl coimand.com, Perl,
?
, $ Perl. ,
Perl, , ,
, . , , ,
(" ") .
, %windir% command.com.

176

II. Perl

,
, :
$myhome=*ls \$"; I 'V $
DOS Windows:
$windows=1dir lwindir%";
UNIX
windir DOS.

qx{} -, :
$myhome=qx' Is $HOME ';
Windows DOS:
$vindows=qx' dir %windir% ';
qx'' Perl : .
,
, .


UNIX DOS/Windows . .
DOS, ( dir Is)
UNIX:
dir > outfile
sort outfile > newfile
more newfile
dir outfile. sort
newfile. , , newfile .
, outfile newfile:
dir | sort j oore
dir sort,
.
more .
(>) BQ ,
!
,
. UNIX
. DOS
Windows , .

11 - .

177

Perl . ,
, ,
, :

dir / | sort j perl Totaler j more


Totaler Perl ( 11.1). . UNIX
dir / Is -1.

11.1. Totaler
1: f!/usr/bin/perl
2:
3: use strict;
4: my($dirs,$sizes,$total);
5:
6: while(<STDIN>){
7:
chomp;
8:
$total++;
9:
if (-d $_) {
10:
$dirs++;
11:
print "$_\n";
12:
next;
13:
}
14:
$sizes+=(stat{$_))[7]j
15:
print "$_\n";
16: }
17: print " - $total, - $dirs\n";
18: print " - ", $sizes/($total-$dirs>, "\n";

.
6.
. $_. STDIN STDOUT . , STDIN ,
dir /.
913. , , Sdirs.
.
1415. $sizes .
1718. ( ,
) .

178

II. Perl

,
, , . Perl open, :
t ' d i r /' ' I s - 1 '
open(RHANDLE, "dir /| sort |"J ] |
die " : $!";
open ,
dir / | sort. ,
, , .
open Perl dir / | sort
sort . RHANDLE Perl .
:
open(HHANDLE, "| more") ||
die " : $!";
open , more. ,
, , . ,
, WHANDLE,
more . , , .
/ RHANDLE WHANDLE, . ,
open.
, ,
Perl .
close , . ,
, :

close(WHANDLE) |} warn " : $!";


; "
open no , ?" UNIX. Perl
,
. ,
, .
, . close , , ,
, .


Perl,
- Perl ,

11- .

179

(VMS, UNIX, Macintosh DOS). , /, Perl


, . .
16- , " ,
Perl.
,
Windows DOS, UNIX. ,
. - .
, Windows UNIX.
, MacOS 9.
, Perl,
, Windows NT, , UNIX. , , .
, ,
Perl ,
Windows NT UNIX.
,
, , , Web-
.
, , , , .
, , ( ) .


use strict. , Perl
, .

. , open 11 die.
open .
,
.

, .
Perl system .

180

(/,
.) Perl,
. , .

II. Perl

.

, 8- , "", use strict .

. , , ?
(no message, or wrong output)
Died at line 15.
Cannot open Foofile.txt: No such file or directory
Cannot open Foofile.txt: No such file or directory at myscript.pl line 24
, .
, ( myscript.pl, 24), , ( Foofile.txt) . .
, .
.
, , , Perl. ,
$dir'dir\
, Windows. <*> opendir/readdir/closedir ( ). .

?
,
, . ,
- .
Perl ,
, . Web- amazon.com,
IBM PC ?
Windows NT UNIX, , 10000
UNIX Sun Enterprise. . ,
CGI- Web-,
. .
, , ,
Windows UNIX? . Perl
$0 ( ,
), , . , Windows DOS KSWin32. UNIX : linux, aix, Solaris, freebsd ..
,
.
- , .

11- .

181

.
, .
, .
, Internet -
, . Perl, Windows
, , :
t ' d i r '
I : 10 dir(s)
67,502,080 bytes free
I windows 98 'bytes' 'MB'
my{gdir,$free);

$free=$dir[$*dirj;
$free="s/.*{[\d,]+) \w+ free/$l/;
$free="s/,//g;
, dir @dir. ,
bytes free. , , , . $free . Windows. UNIX :
'df -k'
:
Filesystem lK-blocks
/dev/wdOsla
31775

Used
21431

Avail Capacity Mounted on


7802
73%
/

, 1024
.
linux bsd
my(Sdir,$free);
dir="df -k .';
$free=(split{/\s+/, $dir[$*dir]))[3];
free*=1024;
. Windows
dir, UNIX df - .. , df ., , ( )
$free. ,
UNIX df ( ) . ,
, Perl.
, Windows UNIX,
,
. , Windows, UNIX.

182

II. Perl

if ($0 eq 'MSWin32') {
t 'dir'
* : 10 dir{s) 67,502,080 bytes free
Windows 98 'bytes' 'MB'
my(gdir,$free);
8dir='dir*;
$free=$dir[$fdir];
$free="s/.*([\d,]+) \w+ free/$l/;
$free=~s/,//g;
} elsif ($AO eq 'linux') {
'df -k'
:
Filesystem lK-blocks
/dev/wdOsla
31775

Used
21431

Avail Capacity Mounted on


7802
73%
/

, 1024
.
linux bsd
my{i!dir,$free);
gdir=df -k .;
$free=(split(As+/, $dir[$*dir]))[3];
$free*=1024;
} else {
warn " \";
}
DOS/Windows
Linux. - ,

. . .
,
.

f
sub freespace {
my(Gdir,$free);

if ($ 0 eq 'MSWin32') {
t 'dir'
: 10 dir(s) 67,502,080 bytes free
Windows 98 'bytes' 'MB'
$free=$dir[$fdir];
$free=~s/.*(f\d,]+) \w+ free/$l/;
$free=~s/,//g;
} elsif ($A0 eq 'linux') {
'df -k'
:
Filesystem lK-blocks
/dev/wdOsla
31775

Used
21431

Avail Capacity Mounted on


7802
73%
/

, 1024

11- .

183

f .
I linux bed
edir='df - .';
$free={split(/\s+/, $dir[$#dir]))[3J;
$free*=1024;
} else {
$free=0; #
warn " \";
}
return $free;
}
, , , freespacef), .
, , . elsif if.

,
.
Perl system. ,
,
') Perl. open
, , . Perl print,
( ) . ,
. , Perl , , .


, , ? (, " | | " ) ?

, . ,

. ,
<> . . ,
, .
, Perl Can't do bidirectional
pipe ( ).
, IPC: :02,
. 14- , " ".

184

II. Perl

$a=system("") $ , , ?
system . . , $= * ;.
UNIX
) ?
, UNIX ( Perl)
: STDOUT STDERR. STDOUT , STDERR
.
open STDOUT. , STDERR STDOUT, :
("

$=' 2>&1'; f
, , 8- Perl.
perldoc perlfaq8.


1.
?
) perl myprog.pl | more.
) open(, "| more") |j die; print M "...\n";
) open(M, ">more") |] die; print M "...\n";
2.

$foo

$r="dir $foo~?
) $foo ;
) $foo Perl, dir.
3. ?
) ;
) ;
) .

11- .

185


1. ) ). ),
myprog.pl
more. ) , ,
more .
2. ). $foo
Perl, qx'dir $foo'.
3. ), Perl glob, <*>
opendir/readdir/closedir, Perl rmdir.

, 8-
, "", 11.1 , .
UNIX, Linux, freespace()
. Linux.

186

II. Perl

12-


Perl
Perl ,
. , perl Perl, .
. ,
, Perl
, "" , . Perl.
Perl ,
. ,
.
.

Perl.

Perl .

Perl
Perl .
Perl , ,
. , ,
, .. : - , .
" ", , . , .

12- . Perl

187


Perl . DOS Windows
:\>. UNIX % $. Macintosh Debugger Script. .
Employee (. 9.1), 9- , " ". 97, . Employee (
DOS):
:\> perl -d Employee
-d, , Perl
. , .
, , :
Default die handler restored.
Loading DB routines from perl5db.pl version 1.07
Editor support available.
Enter h or 'h h' for help, or 4man perldebug' for more help.
main::(Employee:5):
main::{Employee:6):
main::(Employee:7):
main::(Employee:8):
main::(Employee:9):
main::(Employee:10):
main::{Employee:11):

my employs=(
',,123101,9.35,40',
',,132912,10.15,35',
',,198131,6.50,39',
'Her,,141512,9.50,40',
',,131211,11.25,40',
);

( 1.07)
, . ,
my @employees=(, .

( , ), .
DB<1>
. 1 , . Perl
. , ( my f*employees=(), ,
. .

188

II. Perl


, ,
help, .
h,
. h , .
, - .
"" . , |. , ,
|h.
Perl
. ,
, ,
Employee. ,
n (next, ):
DB<1> n
main::(Employee:24):

my ($Ll, $ F l } = e p l i t ( ' r r , $a>;

Perl Employee
( 5 11). ,
, my ($L1, $Fl)=split(',', $); .
^employees. .
, print, :
DB<1> print ^employees
,,123101,9.35,40,,132912,10 5,35,,198131,6.50,3
9,, 141512,9.50, 40, , 131211,11.25,40
,
Perl. , ^employees .
, :
DB<2> print join( H \n", ^employees)
,,123101,9.35,40
,,132912,10.15,35
,,198131,6.50,39
Her,,141512,9.50,40
,,131211,11.25,40
,
, :
DB<3> n
main::(Employee:23): employees=sort {
DB<3> n
main::{Employee:25):
my ($L2, $F2)=split(',', $b);
DB<3> n
main::{Employee:26):
return ( $ cmp $L2 f

12- . Perl

189

main::(Employee:27):

||

I .

main::(Employee:28):
$F1 cmp $F2 f
main::(Employee:29):
);
DB<3>
main::{Employee:23): Gemployees=sort {
, , ,
23 , . , sort , ^employees. , employees (
).
, <Enter>
.


,
.
, Perl . , , .
,
. 1. 10 . 1 10 .. , 1 ,
^ . 1 ,
1 3-10.
, , ===>, :
DB<3> 1 23-33
23==> 8employees=sort {
24:
my ($L1, $Fl)=split(
25:
my ($1.2, $F2)=split{
26:
return { $L1 cmp $L2
27
II
28
$F1 cmp $F2
29
);
30
} ^employees;
31
32:
foreach(@employees} {
33:
print emp($ ]i;

', $a);
', $b);
1
# ...
*

DB<4>

33. , sort
.

190

II. Perl

, , Perl.
( 30),
( 29), ( 31) , .
b _. _ . ,
33, :
DB<4> b 33
DB<5>
,
, (continue, ).
( , ), :
DB<5>

main::(Employee:33):
DB<5>

print_emp($_);

, 33 print_emp.
. ,
print_emp 33.
, :
DB<2>
198131
main::(Employee:3 3):

6.50

39 253.51
print_emp($_);

L, :
DB<2> L
Employee:
33:
break if (1)

print_emp($_);

,
33 Employee.
d, ,
b d ^ d _. :
DB<2> d 33
DB<3>


, print_emp ,
. . R:
DB<3> R

Warning: some settings and command-line options may be lost!


Default die handler restored.
Loading DB routines from perl5db.pl version 1.07

12- . Perl

191

Editor support available.


h or "h h' for help, or 'perldoc perldebug' for more help.
main::(Employee:5):
main::(Employee:6):
main::(Employee:7):
main::(Employee:8):
main::(Employee:9):
main::(Employee:10):
main::(Employee:11):
DB<1> b 33

my (!employees={
',,123101,9.35,40',
',,132912,10.15,35',
',,198131,6.50,39',
'Her,,141512,9.50,40',
',,131211,11.25,40',
);

R . , . 33.
:
DB<2>
main::(Employee:3 3):
DB<2>

print_emp($_);

printemp . , , :
DB<2>
198131
main::(Employee:32):
DB<2> n
main::(Employee:33):
DB<2>

6.50 39 253.51
foreach(Bemployees) {
print_emp($_);

? ,
print_emp? ,
, . "" , s (step, ). , , ,
, . :
main::(Employee:3 3):
DB<2> s
main::print_emp(Employee:14):
main::print_emp(Employee:15):
DB<2>

print_emp($_);
my ($last,$first,$emp,$hourly,$time)=
split(',',$_[0]);

,
print_erap. , , print_emp b print_emp.
, , :
DB<2> n
main::print_emp(Employee:16):
DB<2> n
main::print_emp(Employee:17):

192

my $fullname;
$fullname=sprintf("%s %s", Sfirst, $ l a s t ) ;

II. Perl

DB<2> n
nain::print_emp(Employee:18):
nain::print_emp(Employee:19):
main::print_emp(Employee:20):
DB<2>

printf("%6d *-20s %6.2f d %7.2f\n",


$emp, $fullname, $hourly, $time,
($hourly * $time)+.OO5);


. ,
$2,5, :
DB<2> print $hourly
11.25
DB<3> $hourly+=2.5
DB<4> print $hourly
13.75
DB<5> n

131211
13.75 40 550.01
main::(Employee:32): foreach(employees) {
DB<5>
$hourly (11.25), 2.5 . ,
printf $hourly.
, , , q.

:
. , 12.1, (,
). ,
:

20
19
1
0
- . , , 12.1, . , , Perl (
-w use strict). .
, . ,
message.

12.1.
1: #!/usr/bin/perl -v

2: # .
3: use strict;
4:
5: sub message {

12- . Perl

193

6:
my($quant)=?_;
7:
my($mess,$repl);
8:
$1="";
9:
$mess="B $quant \";
10:
11: if {{$quant < 5)- and ($quant >1 )) {
12:
$1="";
13: }
14: if ($quant eg 1) {
15:
$1="";
16: }
17:
$mess=s/na4eK/$repl/;
18: print $mess;
19: }
20:
21: foreach{20..0) {
22:
Smessage{$_);
23= }
, "".

Perl,
. Perl
,
.
Macintosh , Script 1-liners. .


Perl , -.
Perl, :
C:\>perl -e "print 'Hello, world';"
Hello, world
Perl,
- . :
C:\>perl -e "print 'Hello, world';" -e "print 'Goodbye, world';"
Hello, worldGoodbye, world
He , . ,
Windows/DOS Windows NT command.com cmd.exe

194

II. Perl

,
. , <,>, | , , ,
- . .
UNIX
. , UNIX .
,
\, :
$ perl -e 'print "Hello, World\n";' -e 'print "Goodbye, world\n";'
UNIX, sh, csh,
ksh, bash . . ,
UNIX.

- -d Perl. , :
:\> perl -d -e 1
Default die handler restored.
Loading DB routines from peiU.5db.pl version 1.07
Editor support available.
Enter h or 4h h' for help, or 4perldoc perldebug' for more help.
DB<1>

. Perl ,
. Perl , <Enter>, . (1) Perl.
, 1.


-
, :
:\> perl - Employee
Employee syntax OK
, ,
:
:\> perl - Employee
syntax error at Employee line 13, near ")

12- . Perl

195

sub print^emp "


Can't global t_ in "my" at Employee line 15, near "r$_"
syntax error at Employee line 21, near "}"
Employee had compilation errors.
-w -
.
Perl
.
Web-. ,
, Perl 5.
-v, :
:\> perl -v
This is perl, v5.6.Q built for MSWin32-x86-multi-thread
(with 1 registered patch, see perl -V for more detail)
Copyright 1987-2000, Larry Hall
Binary build 613 provided by ActiveState Tool Corp. http://www.ActiveState.com
Built 12:36:25 Mar 24 2000
Perl may be copied only under the terms of either the Artistic License or the

GNU General Public License, which be found in the Perl 5.0 source kit.
(
Complete documentation for Perl, including FAQ l i s t s , should be found on
this system using %man p e r l ' or 'perldoc p e r l ' . If you have access to the
Internet, point your browser at http://www.perl.com/, the Perl Home Page.

5.6.0
Windows/DOS. ( , ..), Perl -V, :

:\> perl -V
Summary of my perl5 (revision 5 version 6 subversion 0) configuration:
Platform:
osname=HSWin32, osvers=4.0, archname=MSWin32-x86-multi-thread
Compiler:
cc='cl', optimize='-01 -MD -DNDEBUG', gccversion=
Characteristics of this binary (from libperl):
Compile-time Options: MULTIPLICITY USE_ITBREADS PERL_IMPLICIT_CONTEXT PERL_IMP
LICIT_SYS
Locally applied patches:
ActivePerl Build 613
Built under MSWin32
Compiled at Har 24 2000 12:36:25
:
E:/Tools/Perl/lib
E:/Tools/Perl/site/lib

196

II. Perl

, Perl. , , .
@INC. , Perl . , Perl
, "" .
, , 14- , " ".


, .
1. <> ,
, <STDIN>.
2. , <*.bat>, , . , .
.
( ) , , .
, . ( )
" ". :
#!/usr/bin/perl -w
while(<>) <
print $_;
>
Exaraple.pl

:\> perl -w Example.pl filel file2 file3


filel,
file2 file3. , . UNIX, sed, awk .
, Perl (,
-v, -, -d -),
ARGV. , SARGV[ 0 ] " f i l e l " , $ARGV[1] "2" ..
- , -,
:
LINE:
while{<>) {

...If , -
}

12- . Perl

197

, ,
, :
A

:\> perl -n -e 's/ \s+//g; print $_;' filel


Perl :
LINE:
s/"\s+//g;
print $_
}
filel while $_. s/*\s+//g .
- -. . ,
:
A
:\> perl -p -e 's/ \s+//g;' filel
, ,
:
:\> perl - - 's/*\s+//g;' dosfile > dosfile
dosfile
. , dosfile , Perl .
,
, , :
:\> perl - - 's/*\s+//g;' dosfile > tempfile
:\> rename tempfile dosfile
Perl . , , .
The Peri Journal.

, Perl. , , , Perl. ,
- - , Perl.


. Perl?
, . Perl Windows .

198

II. Pert

main::, ?

Perl
. ,
.
Perl - , ?

, . . , perldoc perlrun.


1. , 12.1.
2. , <> :
) undef;
) , ;
) true.
3. Perl . .
? (: , h.):
) ;
) t.

1. 21. (20..>. .. .
21 : for($_=20; $_>-l; $_--).
(0. .20} reverse.
17 $mess=s/na4eK/$repl/;. ,
, $mess. $mess
$_. , = =".
2. ). , <>
STDIN.
3. ). t.
.
, .. .

12- . Perl

199

13-


, Perl .
,
, . (Pascal ) (pointers),
() (indirect references), BASIC Java, ,
. ,
, , , .
Perl ,
(references). Perl ,
,
, , ,
.
.
.
, ( , , ) .
,
,
( . ...).
Perl , .. , .
(, ), , . ,
, . , ,
.
, , . , , .

200

II. Perl

, .


,
:

$=""; f
Perl $ "". , , ? , , $, , .
jJ
, $ , $
$=$,
, , .
[| |!
, . ,
$ $ ,
. .
. ,
! .
, . , $ref
$, :

$ref=\$a; # $
:
$ref
$a
| |
$ref ; ( ) $. ,
$ .
$ , , ($="") (print $).
$ref $,
, , .
, $ref

13- .

201

print, SCALAR(0x0000). 5 $ref,


$ref. , $. .
, $ $ref,
$:
print $$ref;
, , , $ref
, ,
. , $ref.
.
. $ :

$$ref="HoBoe ";
:
$ref

I !
$ref $$ref:
$=!";
$ $ref
"!", .

$ref ,
. , , :
$="";

$nref=\$name;
$oref=$nref;

jf $
$

:
Snref
$name
f|
$name ("") $$nref $$oref. , ,
:
$=" ";
$bref=\$booki # $book
$bref2=\$bref; f $ ( $book!)
:
Sbref2 $bref
Shook
j " |- r>j |

202

II. Perl

, $
$bref2, $$$bref2. , Sbook $bref $$bref. , "" ,
Sbook .


.
, , , :
$aref=\iarr;
$aref @.
:
$aref
~>

garr
0
1
2
3
4
[||&

@ - $aref :
$$aref [0]

G$aref [2,3]

@
@

, , , .
S$aref[0]
@$aref[2,3J
@$aref

,
,
,

${$aref}[0]
{$aref}[2,3]
0{$aref}

,
@ - Saref.
foreach {element ({$aref}) {
print $element;
}


, :
:
$href=\%hash;
$href Gnash.
:

13- .

203

href

lhash

[|]1]11

%hash - $href .
$$href{key}

%hash, key. ${href} {key}

%$href

Shash. %${href}

, %hash ghref :
foreach $key (keys %$href) {

print $$href{$key}; $ To , $hash{$key}


, , .
8- , "", ,
.

J ! 1
sub getarrays {
my (, )_;
}
fruitsqv{86noKO };
fcveggies=qw{ };
getarrays(Hruit, Gveggies);
,
getarrays(Gfruit, Gveggies) Gveggies
fruit, _. getarrays (Ga, )=$_.
Iveggies 8, &b .
getarrays (!_, ,
. .
, , .. getarrays , . :

I !
sub getarrays {
my ($fruit_ref, $veg_ref)=_;
}
?fruit=qw{fl6noKo };
$veggies=qv{ };
getarrays(\8fruit, \Gveggies);

204

II. Perl

getarrays ,
. . getarrays - $fruit_ref, $veg_ref, .
sub getarrays {
my {$fruit_ref, $veg_ref)=_;

print ":", joinf',', $$fruit_ref);


print ":", join(',', S?veg_ref);

,
. , ,
. .
t
sub changehash {
my{%local_hash)=e_;
$local_hash{beast}='nefl8eflb';

return;

%hash=(fish => '',


bird => '');
changehash(lhash);

f
sub changehash {
my($href)=?_;

$$href{beast}='';
return;
>
%hash=(fish => '',
bird => '');
changehash(\%hash);

. _ - %hash. changehash _ %local_hash, , . *local_hash , %hash .


changehash $_
fchash.
$href, , , - %hash.
, $href,
. %hash
beast, ''.
_
. , _
, . , , ,
. , , .
, .


.
. , (

13- .

205

) (,
), . Perl ,
(, ).
* %hash ,
.
my $href;
{

thash=(phone => ', light => '');


$href=\%hash;
}
print $$href{light}; # ""
$href %hash.
%hash , %hash ,
. , ,
,
.
$href %hash (..
, ).
, ,
%hash,
. Perl ( %hash). (anonymous storage), , $ahref.
$ahref={ phone => '', light => '' };
.
, -.
,
" ".
[ ] , .

$aaref=[ qw( ) ];
,
" ".
, -, ,
- ,
.
{ .
my $ref;

$ref=[ qw{0Bec ) ];
)
print $$ref10]; # ""

}
print $$ref[0];

206

t ! $ref

. Perl

, use strict,
. , Perl $ref , ,
, .
-w, , , Perl undefined value (' ),
use strict.

, . , , .

$=[ qw( ) ];
$b=[ qw{ J ];
$=[ gw{ ) ];
$ ,
Smedia=(music -> $, film => $b, 'print' => $);



, .

;
Perl , . , , .

[1]

[2]

[3]

, ,

. ( ), , .

[0] [0]

10] [1]

[0] [2]

[1] [0]

[1] [1]

[1] [2]

[2] [0]

[2] [1]

12] [2]

13- .

207

Perl , . .
,
.
nist_of_lists=(
[ qv( Ford BMW Mercedes ) ],
( qv{ Toyota Mazda Mitsubishi) ],
{ qv( Peugeot Renault) ],
.
Glist_of_lists, . ( )
:

$list_of_lists[0][l]; I "BMH", 1- 2-
$list_of_lists[ll[2]; I "Mitsubishi", 2- 3-
, . , $) , :

$#list_of_lists;
* eiist_of_lists: 2
scalar($list_ofJLists); f $list_of_lists: 3
, . $list_of l i s t s [ l ]
"" list_of_lists. ,
ARRAY(OOOOO). ,
list_oi_lists ,
, .
scalar( 3{$list_of_Hsts[2j} )f * 3- 2-
$#{$list_of_liststl]>;
f : 2

:
foreach my $outer ($list_of_lists) {
foreach Sinner
print "$inner
}

print "\n";
,
.

#
push(f!list_of_lists, [ qw(Lexus Lincoln Chevrolet) ] );
f
push(e{SUst_of_lists[OJ}, qw(Audi) );

208

II. Perl



Perl .
, Perl - , , .
:
, ;
, ;
, ;
, ,
, ..
- . Perl , Perl Data Structure Cookbook. . ,
.
:

.
Perl Data Structure Cookbook
perldoc perldsc.

,
,
.
. Perl , , .
. Perl , . ,
print $mystery_reference;
:
ARRAYf0xl231920)
, $mysterpreference .
, (SCALAR), (HASH)
(CODE). ,
$mystery_reference, . :
print j o i n ( ' , ' i (!{$mystery_reference});

13- .

209

Perl ,
. -,
. - $ref.
DB<2> print $ref
HASH(0xl84b5O)
, $ref . , , :
DB<3> $ref
HASH{Oxl84b50)
'apple' => ' f r u i t '
' c a r r o t ' => 'vegetable'
'pear' => ' f r u i t ' s
, 'apple', 'carrot' 'pear'.
, , :

DB<1> $
ARRAY()
0 ARRAY(0xle8694)
0 'Ford'
1 'BMW
2 'Mercedes'
1 ARRAY(0xlb74cc)
0 'Toyota'
1 'Mazda'
2 'Mitsubishi'
2 ARRAY(0xle8478)
0 'Peugeot'
1 'Renault'
2 'Citroen'

l
#
t
#
# ;
t

$ (ARRAY(0xb33O0)).
ARRAY(0xle8694),
ARRAY(0xlb74cc) ARRAY(0xle8478). .
Data::Dumper . ,
, Perl. ,
, . . Data: :Dumper 14- , " ".

:

, . , .
, . .

210

II. Perl

( , , ). , . .
, , 13.1,
Maze. , 13.2.

13.1.
1: t!/usr/bin/perl -w
2: use strict;
3:
4: @maze=(
5:
[ qw( ) ],
6:
[ qw{ ) ],
7:
[ qw( - ) J,
8:
[ qw( ) ],
9: );
10: my %direction={ '' , [-1,0], '' , [1,0],
11:
'' , [0,1], '' , [0,-1],);
12: my %full=('B' , '', '' , '',
13:
'' , '', '' , '');
14: my($curr_x, $curr_y, $x, $y)=(0,0,3,3);
15: my $move;
16:
17: sub disp_location {
18:
($, $_;
19:
print " ";
20:
while($maze[$cx][$cy] ="/([])/) {
21:
print "$full{$l} ";
22:
}
23:
print "($maze[$cx][$cy])\n";
24: }
25: sub move_to {
26:
my{$new, Sxref, $yref)=g_;
27:
28:
$new=substr(lc($new),0,1);
29:
if ($naze[$$xref][$$yref]l*7$new/) {
30:
print " $new. \n";
31:
return;
32:
}
33:
$$xref += $direction{$new}[0J;
34:
$$yref += $direction{$new}[lj;
35: }
36:
37: until{ $curr_x == $x and $curr_y == $y) {
38:
disp_location($curr_x, $curr_y);
39:
print " ? ";
40:
$move=<STDIN>; chomp $move;
41:
exit if ($move =" /"q/);
42:
move_to($move, \$curr_x, \$curr_y);
43: }
44:
4 5 : p r i n t "! ";

13- .

211

13.2.

?

?

?

?

?

?
!

()
()
()
()
()
()

.
1-2.
Perl. -w , use
s t r i c t Perl
.
49. Omaze, .
4x4,
.
. ,
, ,
. :

J.
\

(2,1) , (jmaze.
, , , , .

212

II. Perl

10-11. .
,
, %direction. , "" 1 , . "" , 1. ( . , .) 33 34 .

1215. , .
use strict. cur_x Scury, (0,0).
(3,3) $ $.

17. ( ).

20. Gmaze ($maze[$cx][$cyj).


,
(, , , ), %full.
()
() .

25. move_to ( $new) .

28.
1, substr .
$new. , , $new , ..

29. ($maze[$$xref ][$$yrefj).


.

3334. . , ,
$direction{B} (0, 1). 0 $direction{B}[0], a
1 $direction{B}[l].

37. .
, ($curr x
$curr_y) $ $ .
38. "" .
3941.
$move, chomp

13- .

213

. q, .

42. moveto,
.
$curr_x
$curr_y .

, @maze. ,
. , ,
. , . , ,
Perl ,
Omaze. $ $. , .

.
Perl:
, , , . , , . Perl .
.


print "dLOL" ARRAY(0xl01210), ARRAY(Oxl014Q0} .. ?
print @array ,
. print "fULOL" 9L0L, .
,
@LOL, , " ,
" .
$ref=\($a, $, $). $ref , ?
Perl \{$, $, $) (\$, \$,
\$)! $ref , , .. $. ,
$ref=[$a, $b, $c].

214

II. Perl



1. Sref
$=\"";?
) , ;
) "";
) .
2. ?
$=[

{ ==> "", kids==> [ *(, , ) ]},


{ name==> "", kids==> [ qwfCama, , ) ]},

,
) , , ;
) , ;
) , .

1. ). ,
, . ,
$ref=\100; . , ,
, .
2. ). , , , , (
kids).

Maze ,
. ,
, , .
:
maze, %full
([1,1], [-1,-1] ..) ^direction.
( ), . () (, , ),
, . ( ) .

13- .

215

14-

Perl, , , , , , , . , , , ,
. Perl ". .
, Perl,
. Perl (
, system), 11-
, " ". - ,
.
. , , ,
. , ,
World Wide Web. , , ,
. 10 Web , , , .
Perl . Perl 5,
. Perl,
. , , Web-, ,
Windows OLE,
, . , Perl . .

, .
, CGI-
Perl.

216

II. Perl

3500 ,
Perl 20 .
, ,
, . , ,
, - . , , .
.

Perl.

, Perl.


Perl, use. , Cwd,
:
use Cwd
, , use Cwd.
.
Cwd 10- , " ".
, . ,
use Cwd, .
1. Perl
, use Cwd.
2. Perl ,
. Perl Cwd. , Perl.
3. Perl , , .
4. Perl
, use.
. Perl , , , .
, , , use s t r i c t use
Cwd. , : use , "" Perl . use strict, ;
s t r i c t . use Cwd
.
.
onepaTop'use Cwd,
cwd. .

14- .

217


Perl . ,
, , , , .
, perldoc,
. , cwd, :
perldoc Cwd
.
( ).
Cwd(3)

13/Oct/98 (perl 5.005, patch 02)

Cwd(3)

NAME
getcwd - g e t pathname of current working d i r e c t o r y
SYKOPSIS
use Cwd;
$dir = cwd;
use Cwd;
$dir = getcwd;
use Cwd;
$dir = fastgetcwd;
DESCRIPTION
The getcwd() function re-implements the getcwd(3) (or
getwd(3)) functions in P e r l .
The absjpath() function takes a s i n g l e argument and returns
the absolute pathname for that argument. I t uses the same
a l g o r i t h n a s g e t c w d ( ) . ( a c t u a l l y getcwd() i s abs_path(".J)
, Cwd
: cwd, getcwd fastgetcwd. ,
Cwd.
, , . Perl . , Cwd Cwd.pm. , , Perl. @1. , perl -v.
, Perl, ,
.
, ,
, , LWP,

218

II. Perl

.
,
. ,
1- , " Perl", ,
, .

?
Perl
, . , , , - , .
:
syntax error in file XXXX at line YYY, next two tokens "use Cwd'
, Perl .
:
perl -v
Perl 5 , 4,036,
, Perl, . Perl 5. , . , 13- , " ", Perl 4.
Perl 4, . .
:
Can't locate Cwd.pm in SiNC (8INC contains: path.. .path.. .path...)
BEGIN failedcompilation aborted
.
(, ).
, .. use Cwd use
cwd .
(::) File: :Find, .
, , .
Perl 150
" ".
. .
,
.
, " Perl" ,
.
Perl ,
.
, .

14- .

219

Perl , INC. ,
- , Perl. ,
, . , , , . ,
, .


,
Perl .


10- , " ", ,
, .
, . ,
.
, ,
. ,
important.doc, documents, :
/documents
-/accounting
/1998
/1999
/2000
7misc
-/personal
,
documents. ,
documents, opendir/readdir/closedir .
documents.
, documents, accounting, misc personal,
, , ..
, 30 .
. , Perl ,
File::Find. ,
(, ) :
use File:-.Find;
find. :

find subref, dirlist

220

II. Perl

,
. ; .
, :
, .
, &.. ,
find,
dirlist.
14.1 important.doc.

14.1.
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:

J!/usr/bin/perl -w
use strict;
use File::Find;
sub wanted {
if ($_ eg "important.doc") {
print $File::Find::name;
}
}
find Uwanted, '/documents';
.

1-2.
Perl. -w , use
s t r i c t Perl
.

3. File::Find.
find.

5. , /documents. ,
100 12 , wanted 112 .

6.

wanted(),

$File: :Find: :name


, $_ . ,
important.doc; ,
.

10. find Uwanted , .


wanted () ,
/documents.
, find, .
$File::Find::name (
);
$File: :Find: :dir ;

14- .

221

$ ( ). , $_ .
, .
14.2 File::Find.
.tmp : D:. ""
.
, UNIX,
.

14,2.
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14t
15:

/usr/bin/perl -w
use strict;
use File::Find;
sub wanted {
f , :
if ( -f $File::Find::name ) {
f ".tmp"
if ( $File::Find::name="7\.tmp$/i) {
print " $File::Find::name";
unlink $File::Find::name;
}
}
}
find(\Svanted, 'c:/', 'd:/');
, 14.2,
14.1. .
7. , wanted, , . , , .
911. , .tmp. , unlink.



Perl .
1. .
2. .
3. .
4. .

222

II. Perl

, , ,
,
. Perl File::Copy, . .
use File::Copy;
copyfsourcefile", "destination") 11
warn " : $1";
sourcefile
destination. 1 0, - , $! .
File::Copy move- move .
,
. move
,
. -
, move , . :
use File::Copy;
if {not move("important.doc", "d:/archives/documents/important.doc")) {

warn " important.doc: $1";


unlink "d:/archives/documents/important.doc";

>
important.doc
d:/archives/documents. move ,

important.doc. move unlink
.

! -?
Perl . , Net::Ping ,
.
Net: :Ping ping UNIX. "ping", ,

. ping .
, ,
ping . Net::Ping, 1
, .
use Net::Ping;
if ( pingecho{"www.yahoo.com", 15) ) {

print " Yahoo .";


} else {
print "C Yahoo - ...";
}

14- .

.'

223

, Net: :Ping
pingecho. . ,
( www.yahoo.com). , ( ) pingecho .
- Perl Windows 95/98/NT ( 1999) Net: :Ping .
alarm, Windows, tivestate Perl Windows
Windows Perl.

, , -!
English Perl
, :
use English;
while(<>) {
print $ARG;
}
while{<>)
STDIN $ . . use English $_ $ARG. .

$ARG

$!
$'0

$OS_ERROR
$OSNAME

$0

$PROGMMJME


English.


diagnostics Perl .
, , Perl , . ,
fl/usr/bin/perl -v
use strict;

print " helpGsupport.org\n";


224

II. Perl

Perl :
In string, isupport now must be written as \8support at line 4
Global symbol "^support" requires explicit package name at line 4
diagnostics Perl . -,
:
#!/usr/bin/perl -w
use strict;
use diagnostics;

print " help0support.org\n";



:
In string, Isupport now must be written as \Gsupport at line 4
Global syiibol "^support" requires explicit package name at ./diag.pl line 5 (#1)
(F) You've said "use strict vars", which indicates that all variables
must either be lexically scoped (using "my"), or explicitly qualified to
say which package the global variable is in (using " : : " ) .
, ,
. . Perl ,
help\0support.com. , , .
use strict, ^support .
, (Isupport , ,
Perl.
. (W) , (D) ,
(S) , a (F) . Perl
, (F).
Perl 60
. , Perl ,
use diagnostics.

perldiag Perl.

, Perl,
. ,
Peri, . ,
, perldoc, .

14- .

225

Autoloader

Perl

AutoSplit
Benchmark
CGI



Perl
CGI Web-, III, "CGI Perl",

CPAN

Perl

Carp

DirHandle

Env

Perl

Exporter
Extutils::*

File::*

,
File::Copy
,

File::Spec::*
FileCache

FindBin

Getopt:: *
I18N::Collate

IPC::*

Math: :*

Net::*

. ,
Net::hostent IP-, 204.71.200.68, , www.yahoo.com

Pod::*

Perl

Symbol

Perl

Sys:: Hostname

,
IP-

Sys::Syslog

UNIX

226

II. Perl

Term::*

, ..

Text::Abbrev

Text::ParseWords

Text::Soundex


Soundex

Tie::*

Perl ,

Time::*

.
, , Sat Jul
24 16:21:38 EDT 2000, , 0 1
1970

constant

integer

Perl
,

locale


, , , Web-
http://www.cpan.org.
.
. , Windows. Perl Activestate
,
.

, UNIX Windows. , CPAN ( UNIX) Activestate .

, Peri. .
Perl . ,
, , Perl.

14- .

227


(::) File::Find,
$File::Find::dir?
Perl , . ,
.
Cwd $Cwd::x. , . , $ $main::x.
.
Windows 95/98/NT,
Activestate. ?

, UNIX ; , Windows.
,
; .
Perl, use
require. require?
require use. Perl 4 use,
require. require
use. , require , use
(.. ).


1. cwd ,
use Cwd;?
) ;
) cwd, ..
;
) , cwd .
2. $_?
) LongVars
) English
) $ .

223

II. Perl


1. ). use, .
2. ). use English , $ $ARG.

Bundle: :LWP CPAN. , 24- , " Web-".

14- .

229

15-

Perl
,
,
. - : "
, , ?" , , . ,
.
- .
, . , , .

. , , : ,
.
, .
.

DBM- .

, .

DBM
Perl DBM- . DBM
Perl -

230

II. Perl

. DBM- , 7- , "".
DBM-, Perl dbmopen, :
dbmopen(, ^, _)


DBM-. _
: _ , __.dii. Perl
. ,
.
, ,
.
.
dbmopen ,
DBM- . UNIX
_.
DBM-. , , 0666, DBM- ; 0644 ,
.
Windows ,
. 0666.
dbmopen , DBM- . :
dbmopen(%hash, "dbmfile", 0644) ||

die " -: $!";


%hash DBM dbmfile. Perl : dbrafile.pag
dbmfile.dir. ( ), Perl
DBM-:

$hash{''}="";
$hash{''}="";

DBM-, :

print $hash{''};
%hash DBM-, dbmclose:
dbmclose(%hash);
' ' ' '
DBM-.
%hash DBM- .
, DBM-, ,
, keys, values delete.
( DBM-), , :

15- . Perl

231

%hash=();
DBM-, dbmopen .


,
DBM-.
. Perl ,
, DBM-
1024 . DBM-.
, .
dbmopen
.
. :
%h=();

$h{''}*"";
dbmopen(%h, "dbmfile", 0644) ||
die " DBM-: $1";
print $h{''}; t
dbmcloee(fth);

dbmopen ''
%h .
dbraclose . :

dbmopen(%h, "dbmfile", 0644) ||


die " DBH-: $1";
$h{'')="";
dbmclose(%h);
print $h{''>; $

'' DBM-.
dbmclose , %h .

DBM-
, DBM-. , Perl ,
: , , . , ,
. , DBM-,
. , , .

232

. Perl

DBM-, records, ,
.
dbmopen(%recs, "record", 0644) J|

die " DBM- record: $1";


foreach my $key {keys Irecs) {
print " $key = $recs{$key}\n";
}
dbmclose(trees);
He , ! %recs
DBM-, keys %recs
, foreach my $key .
%recs , keys %recs - . Perl , . each. :
($JMK>, $ ) = (%);
each , , , . . , . , , :
dbmopen{*recs, "record", 0644) ||

die " DBM- record: $!";


while( ($key, $value)=each Irecs) {
print " $key = $value\n";
}
dbmclose(*recs);
each ,
, DBM-.

:

, ,
. . memopad, 15.1.
, . memopad 15.2.
memopad . , X is ,
X , ,
. "like ?",

15- . Perl

233

, !. ,
. quit. ,
DBM-, memopad .

15.1. memopad
1: t!/usr/local/perl -w
2: use strict;
3:
4: my(%answers, $subject, $info, $pattern);
5:
6: dbmopen(%answers, "answers", 0644) [|
die " DBM- 'answers': $1";
7: while{l) {
8:
print " 'quit' : ";
9:
chomp($_=lc(<STDIN>));
10:
last if (/Aquit$/);
11:
if {/like\s+{.*)\?/) {
12:
$pattern=$l;
13:
while( ($subject,$info)=each(%answers) ) {
14:
if ($subject=~/$pattern/) {
15:
print " '$pattern' '$subject'\n";
16:
}
17:
}
18:
} elsif(/(.*J\?/) {
19:
$subject=$l;
20:
if ($answers{$subject}) {
21:
print "{subject - $answers{$subject)\n";
22:
} else {
23:
print " $subject \";
24:
}
25:
} elsif(/{.*)\sis\s(.*}/) (
26:
$subject=$l;
27:
$info=$2;
28:
$answers{$subject}=$info;
29:
print " , Ssubject - $info\n";
30:
} else {
31:
print " \";
32:
}
33: }
34: dbmclose(%answers);
15.2. memopad
'quit' : perl?
perl
'quit' : perl is
, perl -
'quit' : Web- perl is http://www.perl.org
, web- perl - http://www.perl.org
234

II. Perl

' q u i t ' : perl?


perl -
' q u i t ' : like perl?
' p e r l ' ' p e r l '
' p e r l ' 'web- p e r l '
' q u i t ' : quit
.
12.
Perl. -w , use
strict Perl
.

6. ^answers DBM- answers dbmopen.


answers. answers.dir.

7. while(l) . last.

9. ,
. 1
. <STDIN> 1,
,
$_. chomp
$_ .

10. quit, while .

11. ( $_)
like, , , $1 (
).

12. , ., $1, Spattern.

13-17.
%answers , , $pattern. .

18. if,
11 . , .
$1.

19. , $1, Ssubject.


2024. ^answers , Ssubject,

15- . Perl

235

. ,
.

2527. 25 if,
11 . , .X is Y. X $subject, $info.

28. , $info,
^answers , $subject.

34. dbmclose ^answers


DBM-.



, . , , Web-
. , . , .
. ,
DBM- Oracle
Sybase. .
, , .
.

, - .

,
.


, .
, .

, , .
, . , , .
, .
.
555-1212
555-0912

236

II. Perl

555-0012
555-1190
:
[]555-1212[ ][]555-0912[ ] . . .
[] [ ] . ,
, , .
,
. , ,
,
Perl .
, ,
.

.
.
. , ,
555-1212 555-613. []555-0912[ ] . . .
, 555-1212
555-613:

[]555-1212[ ][]555-613[ ]
[]555-0912[ ] ...
, , (
).
.


, . ,
. , , 5550912 . :

[]555-1212[ ][]555-0012[ ]
[]555-1190[ ]


. DBM-, ,
,
.
.

15- . Perl

237


,
, .
' , ' .
,

555-1212
555-0912
555-0012
555-1190

phone.txt, Perl , , .
:
f!/usr/bin/perl -w
use strict;
sub readdata {
open(PH, "phone.txt") ||

die " phone.txt: $1";


my(gDATA)=<PH>;
chomp I!DATA;
close(PH);
return ();

}
readdata{} phone.txt
@DATA.
. , writedata(), , . writedata() :
sub vritedata {

my{f!DATA)=l!_; $
open(PH, ">phone.txt") ||
die " phone.txt: $1";
foreach(8DATA) {
print PH "$_\n";
}
close(PH);

}
, ,
readdata(), .
push, unshift splice.
,
writedata(), :
(!PHONELIST=readdata{);


* ePHONELIST
pUSh(ePHONELIST, " 555-1314");
writedata{0PHONELIST); *

238

II. Perl

, splice, pop
shift @PHOKELIST, .
, ,
grep, :

ePHONELIST=readdata(); |
I PBONELIST
# , ""
$PBONELIST=grep(! //, SPHONELIST);
writedata{ePBONELIST);

readdata() @PHONELIST. grep ,
. ,
, &PHONELIST. writedata (}.


, , .
.
. , .


,
. , , . . 15.1.

15.1.
open

open(F, "<file ")

open(F, " f i l e " )


open{F, ">file")

open(F, " f i l tsH)

open(F, "+<fil<")
open(F, "+>fil(>.")

open{F, " + f i ]Le")

15- . Perl

239

, . ,
UNIX, , , , . ( , ,
.)

+>,
.




, /.
, . ,
, .

, .


seek. : , , . : 0
, 1 , 2
.
seek().

#
open(F, "+<file.txt") || die " file.txt: $1";
seek(F,0,2); I
print F " "; I
seek(F,0,0); i
print F " "; 1
, t e l l .
, tell(F)
16 ( " "). ,
.

240

II. Perl

seek, t e l l open,
.
. perlfunc Perl.
perldoc perlfunc. ,
open perlopentut
Perl. perldoc perlopentut.


, Perl , . ,
(UNIX, Windows NT Windows 9x),
, . Web-,
, .
, ,
, , , .
,
. ,
, .
chomp($newrecord=<STDIN>);
ePHONEL=readdata();
push(PHONEL, Snewrecord};
writedata(PHONEL);

#
t


IJPHONEL

, ? ,
,
.
. , . .

1
1 5=" 555-1212";
2
epHONEL=readdata();
3
push(PHOSEL,Snewrecord);
4
writedata{PHONEL);
5

2
$=" 555-6611";
gpeoNEL=readdata();
puBh(iPHONEI,,$newrecord);
writedata(ePHONEL);

, , " 555-1212" PHONEL ,


.
, , " 555-6611" 8PHONEL ,
8PHONEL .
: ,
, " 555-1212",
. , "

15- . Pert

241

555-6611" . 6PH0NEL,
GPHONEL, " 555-1212".
"" ,
"" , . , " 555-6611",
" 555-1212", .
, . . ,
writedata() . .
( !)
, . , , . ,
.
-
" 1".
, , .
.
, . , . , . ,
,
,
,
. , .

UNIX Windows NT
UNIX Windows NT
Perl flock, . , , - ,
flock , . , ,
. .
.
, . . , .
. ,
,
flock -

242

. Perl

. ,
,
.
flock , .
use Fcntl qw(:flock);

_6);
flock , . .
flock
. . use Fcntl
qw(; flock)
.
: . ,
. -
, ,
. ,
.

flock.
LOCK_SH
. - ,
flock LOCK_SH .
, , .
LOCK_EX , . -
( ),
flock LOCK_EX
.

LOCK_UN . , ,

. ,
.
, flock, (
).

, ,
. ,
. ,
, . , -

15- . Perl

243

open(FH, ">filename"),
flock,
(
>). , , .
( , ; ).
.
,
15.3. , .

15.3.
useFcntlqw(:flock);

my $semaphore_file="/tmp/sample.sem";

\ ( )
sub get_lock {
open{SEM, ">$semaphore_file")
|| die -" : $!";
flock(SEM, LOCK_EX) jj die " : $1";
}
I
sub releaseJLock {
close(SEM);

15.3
, ,
( ),
. , ,
.

get_lock();
I ,
print "Hello, World!\n";
releaselockf}; $
get_lock() release_lock{), , .
,
, . .

244

II. Perl


readdataf) writedataO,
.
- get_lock() release lock{),
. 15.4.

15.4.

1: f!/usr/bin/perl -w
2: use strict;
3: use Fcntl qw(:flock);
4:
5: my $semaphore_file="/tmp/listl54.sem";
6:
7: f ( )
8: get_lock {
9:
open{SEM, ">$semaphore_file")
10:
|| die " : $1";
11:
flock(SEH, LOCK_EX) || die " : $!";
12: }
13:
14: jf
15: sub release_lock {
16:
close(SEH);
17: }
18:
19: sub readdata {
20:
open(PH, "phone.txt") ||
die " phone.txt: $!";
21:
my(fDATA)=<PH>;
22:
chomp{?DATA);
23:
close(PH);
24:
return(eDATA);
25: }
26: sub vritedata {
27:
my{DATA)=_;
28:
open(PH, ">phone.txt") \\
die " phone.txt: $1";
29:
foreachfgDATA) {
30:
print PH "$_\n";
31:
}
32:
close(PH); *
33: >
34: my ;
35:
36: get_lock{);
37: PHOHEL=readdata();
38: pushfSPHONEL, " 555-1012");
39: writedataf gPRONEL);
40: releaseJLockf);
15- . Perl

245

^'^ 15.4 .
'-! get_lock{), release_lock(), readdata() writedata()
.
34. getJLock{). readdata()
GPHONEL,
writedata(). , release_lock(}. .

Windows 9x
, Windows 95/98 .
? , , . , flock Windows 9x,
:
flock() unimplemented on t h i s platform at l i n e . . .
( flock{) ...}
, Windows 9x .
, ,
get_lock() release_lock().
Windows 95 98 , ,
, flock . , , get_lock() release_lock{).
.

UNIX
Windows NT
,
, flock -
. , flock
, , . , UNIX (NFS). ,

UNIX Windows. flock UNIX Windows.
flock 5, "Files and Formats", Perl.
perlfaq5 Perl.

246

II. Perl



. DBM Perl,
.
. , .


, 13- , "
", DBM- ?
, , , .
"" , , . , DBM-. Perl , . Data::Dumper.
DBM-?
DBM- ,
. get_lock{) release_lock(), 15.3. DBM-
, :
get_lock();
dbmopen(%hash, "foo", 0644) [J die "dmbopen: $!";
$hash{newkey}="3Ha4eBHe";
dbmclose(fthash);
release_lock(};
- , flock
?
, . flock , .
flock . ,
flock , L
| OCK_NB
, ,
use Fcntl qw{:flock);
*
I
if (not flock(LF, LOCKEXJLOCKJffi)) {
print " : $!";
}

,
, ,
. :
use Fcntl qw(:flock);
$lock_attempts=3;
While {not flock(LF, LOCK_EX|LOCK_NB)) {

sleep 5; t 5
$lock_attempts~;

die " !" if (not $attempts);

15- . Perl

247



1. , DBM-, .
) ;
) .
2. ?
)
;
) ;
) , .
3. ?

1. ). DBM- 1024 .
2. ).

.
) , ,
.
3. 5, "Files and Formats".

248

, , . , ,
1 . ,
.

II. Perl

16-
Perl
. , , - Perl.
,
. ,
, . '
Perl, Perl.
, Perl, ,
, , , Peri , . ,
, .
.
Perl.
CPAN .

Perl?
Perl, , Perl , , Perl.

Perl
1988 Internet . -, , -, "" , . Internet
60 000 .
10 .
(WWW) .
1991
(CERN), , Mosaic, 1993 .

16- . Perl

249

Internet . Usenet ,
.
, , .. . Internet telnet.
1988 , , awk sed UNIX "Perl".
Perl .
Perl ,
,
.
. Perl , . , , , , ,
. Perl ( ,
) , sed, awk sh, ,
, . ( csh, Pascal BASIC-PLUS.)
Perl .
, sed, awk sh, ,
, , , , ,
Perl. , , sed- awk- Perl-.
Perl 1988 .
Perl: Perl 2 . , . , Perl
.
Perl 1991 .
Programming Perl, (Randal Schwartz).
( , ) Perl.
Perl. ( , , .)
Perl 4.
Perl, ,
1992 . , .
1994 Perl.
, , , (
). 1996 Programming Perl
("The Blue Camel" " ". . .)
.


Perl . Perl ,
(open source). , ,

250

II. Perl

. ,
, - , ,
. , , Linux FreeBSD,
Web- Apache Mozilla.
. ,
, ,
, ( ). , , , .
, .
. {Eric S. Raymond)
. , .
, "The Cathedral and the Bazaar" (" "
. .), ,
. URL
"" .
Perl ;
, . , , Peri
() .
, ; , ,
, . : GNU
General Public License Perl Artistic License. , Perl.
, .

Perl,
.

,
, , Perl. Perl.

Perl.
, Perl
. Perl , .

, Perl, .

Perl .

;
,
.

16- . Perl

251

Perl ,
, , . Perl Artistic License Perl Artistic. GNU
General Public License Web-
http://www.gnu.org.
Perl
. , Perl , - . , ,
.

Perl
, ,
Perl, , Perl ,
, Perl.

. , , "" , Perl.
, Perl, ,
, .
, ,
, , .
Perl .
1999 major.minor_patchlevel. , 4.036_18
Perl, 36 "" 18.
"" . Perl 2000 5.6.
major.minor.
, Peri 5.7 ..

Perl (CPAN)
Perl , CPAN (Comprehensive Perl Archive
Network).

?
Perl (Comprehensive Perl Archive Network CPAN)
Perl. ,
Perl , .
, CPAN, .
CPAN ,

252

II. Perl

3500 . . . 16.2 ,
, CPAN.
, . , CPAN, ;
.

16.2. , CPAN

Perl-. , Win32 API, Gtk,


Gnome, Qt, 11

Net::*

. Mail, Telnet, IRC,


LDAP 40

Math::*

30 , ,
, ..

Date::*, Time::*

Data::*, Tree::*

DBI::*
DBD::*

, Oracle, Informix, Ingres, ODBC, Msql, MySQL Sybase


Term::*

,
MS-DOS Windows X- UNIX

String::*, Text::*

CGI::*,

, ,
Web-

URL::*,
HTML::*,

LWP::*
GD,Graphics::*, Image::*

Win32::*,Win32API::*

Microsoft Windows

, CPAN, . README, ,
, . , Perl, Artistic License GNU General Public License.
CPAN , Perl.
CPAN " Perl".

16- . Perl

253


Perl?
,
, . , , , , 50 XX .
20 30 - .
; " ". ,
, .
,
, ,
. ,
.
,
, .
CPAN Perl . , , ,
- "".
, ,
Perl, .
, .

, ,
- .
, CPAN .
, CPAN, .
, . , .
,
, .. ,
.



Perl. , .
Perl, .. 2300 ,
Perl ( ),
.
,
Perl. ,
.
, , , . , ,
, .

254

II. Perl


- Perl, , .
, , . ,
, . , ,
. ,
, . , .
, , .
.


Peri Perl.
, . , : .
, , ,
: - ,
. ;
Perl , - .
, .
Perl ,
? , ! Perl .

, (, ) ?

? .
, ,
.
, - ? , ?
, ?
.
,
, , ?
- , ? , . , , .
Perl ,
, , , .
, .
1. , #! -w.
2. , - use strict.
, ,
, , -w use strict. , , ,
.

16- . Perl

255


, , , .
, ,
print.
, , .. , . ,
print :
sub foo {
my($al, $a2)=g_;
I
print STDERR ": foo $al $2";
}
,
print. , - , DEBUG .
, STDERR,
. LIKE FILE , Perl .
, , Perl.
, Perl. .
Perl 12- , "
Peri".

-,
, ,
, , , , ,
.
Perl.
1- , " Perl", Perl
. 5.6 1700
.
Perl, .. ;
(Frequently Asked Questions FAQ).
,
perldoc perl. ,
Perl.
FAQ Peri, .
, ,
, .
-
Perl perldoc ,
.
, , Perl, . , , - .
, Web- http://www.perl.com.

256

II. Perl


Usenet ,
80- Internet,
. Usenet ,
, , , . . , Perl.
.lang.perl.announce

Perl,

. lang.perl.moderated

, ,
Perl, ,

.lang.perl.misc

, , Perl

Usenet, . . , , . Web- (, deja.com supernews.com),


Usenet Web;
Web-.
, Perl,
. , ,
Perl, .
, : " ". ,
- . ,
, . ,
, , .
deja.com Usenet. , , , , .
. , , Perl, "" Web-. Power Screen
deja.com :
Keywords: fetch web page
Forum: .lang.perl.misc
.
100 ,
, . , Usenet, .

.
. ,
. , ,
.

16- . Perl

257

, .
, , ,
, .

deja.com . ,
, .

,
, , Usenet
, - .
, .
.

. , , ,
. , , , ,
.
, , , , , . ,
- ,
.
Usenet,
Web-. ,
.
1. - , ,
. , Perl,
. , Perl.
, FA.Q
deja.com, .
2. , , .. .
Perl .lang.perl.misc. A
, CGI, ,
.infosystems.www.authoring.cgi. FAQ , ,
.
3. 1 Subject.
.
( "" " "); , .
4. :
) , (, ,
, );
) , ;
) , .

, ,

258

II. Perl

, .
, .
:
) ;
) , .-,
uuencode;
) MIME. .
5. , , , .
6. , , .
. . ""
"" , - . , . , "
CGI-..." " Web-,
...". .
, .
, Usenet .
, . , , . , 1 ,
Usenet . ,
. , , Subject, .
(
) . , . , .
, .

, , .


Perl, Perl
Perl, .

Larry Wall, Tom Christiansen, Randal Schwartz, Programming Perl Perl .


Perl, .

Tom Christiansen, Nathan Torkington, Perl Cookbook, ,


, , . , , .

The Perl Journal. , ,


" Perl". ,
Perl (, -

16- . Perl

259

Perl ), .
: " [...],
, Perl, , ..."
.
Internet History ( Internet): Hobbe's Internet Timeline
http://www.isoc.org/zakon7lnternet/History/HIT.htinl
History of Perl ( Perl): CPAST
http://history.perl.com
The Perl Journal
http://www.tpj.com
PAN
http://www.perl.com/CPAK

. . http://www.perl.com
.
http://www.netaxs.com/~esr/writings

Perl Perl . , CPAN, . , , ,


- Perl.


Web Perl, CGI?

Perl CGI- ,
( ),
. , Perl CGI-.
Usenet , .

?
, - ?
, , .
. , " ".

260

II. Perl

CPAN?

! Web- http://search.cpan.org . , .


1. Usenet CGI- Perl?
) comp.infosystems.www.authoring.cgi;
) .lang.perl.misc.
2. , ,
, ?
) ;
) .lang.perl.misc;
) ,
http://www.perl.com.

1. ). .lang.perl.misc , , CGI-, .
2. ) ), , , .
, . www.perl.com
.

16- . Perl

261

III
CGI- Perl

17

CGI

264

18

278

19

291

20

HTML- CGI-

302

21

cookie

318

22

CGI-

332

23

Push-
Web-

345

24

Web-

357

17.-
CGI
Internet , , World Wide
Web. Web- 1993 Internet
. Internet 20 , 12 . , intranet,
.
Web 1993 .
Web , Web-. Web Web- .
CGI . CGI Common
Gateway Interface ( ).
HTML. HTML . , , .
HTML Web-. HTML
, ,
Web. , HTML <i>He</i> < i x / i > . . (
) Web- .
HTML .
, . HTML World Wide Web (W3C), Internet
http://www.w3c.org. Web- HTML. HTML
HTML 4. ,
"".
264

III. CGf- Perl

Web.

, CGI-.
CGI-.

Web
Web ,
. , Web-,
. Web, Netscape Communicator, Internet Explorer, Opera -
. World Wide Web. Web- Web-.
Web- , Web-.
, Web-. ,
, . 17.1.
Web-

Web-

. 17.1. Web- Web-

Web-
Web- URL (Uniform Resource Locator ),
. URL :
http://www.google.com:80/more.html
URL .
http

HTTP Web-. URL ftp HTTP (https, secure HTTP).


www.google.coin , .
.
IP-, , : 209.185.108.147. World Wide Web IP- , , .

:80 ,
. URL . , , . , http 80.

17- . CGI

265

more.html . .
, /archives/foo.html,
? . , .
URL, (. 17.2).
1. (ww.google.com) IP-
(209.185.108.147).
2. IP- .
3. more.html. .
4. , more.html, .
5. .
DNS

more.html

more.html

ww.google.com
( 209.185.108.154)

. 17.2.

20- , " HTML- CGI-".

CGI Web-
Web-
(. . 17.1 ).
, . 17.1, , .
Web- CGi-. CGI Web- ,
HTML-. URL ,
CGl- , , Web-, , . 17.3.

266

III. CGl- Perl

Web-

CGI

==
. 17.3. Web-, CGI
, CGI-, .
1. CGI-.
2. , ,
.
3. .
4. CGI- .
CGI- ,
Perl (
CGI- Perl).
: , UNIX, Pascal,
LISP, TCL. , CGI- Perl, . Perl ,
, CGl- .
, CGI- , : ,
HTML, zip-, Web.
CGI- HTML.
CGI , . Perl, HTML HTTP. CGI
Web- . CGI Web-
http://www.ncsa.uiuc.edu/cgi/interface.html.
, .


CGI-.
, CGI, , . .
, CGI- Web-. CGI- Web-.
Web- :
Web- .
: ,

.

17- . CGI

267

Web-, Internet. Web-.


. CGI- Perl , Web- Perl 5
CG 1-. , Web, Perl CGI
CGI. .
, . CGI- , , .
.
, CGI-. , Web- ,
.
Web- ,
.
Web-. Windows
Web-.
, Perl CGI. Windows
Web-, Microsoft Internet Information Server (IIS).
UNIX Web-.
UNIX.
Internet Web- Apache . Web-
Apache , . Apache Windows-. Apache http://www.apache.org.
CGI- Web-, ,
Web-. Web- Web-, , CGI- .
Web- ,
CGI-. CGI CGI-.


, Web- Web-, . , ,
.

268

Web-,
.
Web-, ,
.
, Web-.
CGI .

Web- .
.

ill. CGI- Pert

CGI-.
Perl Web-.
#1 CGI-. Web-, Windows, .
' Web-;
CGI-, Web. , .

CGI-. Web- ,
Web- CGI-, . CGI- .cgi
.pi, .

CGI-. Web-
CGI- ,
. CGI-. CGI- /cgi-bin, Web-.

URL CGI-. CGI-, ,


URL Web- , CGI
http://www.myserver.com/cgi-bin/ http://www.myserver.com/cgi/.

CGI-
, , , CGI-.
17.1.
hello.
, .. .cgi, hello.cgi. .pi, hello.pl.

, ?

17.1. CGI-
1:
2:
3:

JH/usr/bin/perl -w
use CGI gv(:standard);
use strict;

4:
5:
6:

print header;
print "<B>Bello, World!</B>";

.
1. . , ,
Perl ,
. -w .

17- . CGI

269

2. CGI, . qw(:standard)
, .

3. use strict .
, CGI .

5. CGI header.
, ,
CGI-.

6. , CGI, . ,
, Hello, World.
? , . CGI- . .

CGI-
CGI- , FTP- .. CGI-.

Web- UNIX
UNIX- Web- telnet,
rlogin - , .
1. CGI- hello.cgi ( hello.pl) UNIX- FTP. vi.
2. CGI- mv .
.
3. UNIX .
:
chmod 755 hello.cgi
hello.cgi ,
hello.pl. chmod . ,
(
CGI-).

FTP- Web- UNIX

FTP- .
1. FTP- hello.cgi ( hello.pl)
CGI- . .
ASCII. He CGI-
. FTP .

270

III. CGI- Perl

2. CGI- . FTP

quote site chmod 755 hello.cgi


hello.cgi .
.
,
.
3. FTP-, Cute-FTP,
Set Permissions, Change Mode, Set File Attributes Set
File Access Mode .
4. ,
, , . FTP- , 755.

Web- Windows NT
Web- Windows
NT, CGI- , . .

FTP- Web- Windows NT


FTP- Web- Windows NT FTP, hello.cgi ( hello.pl) CGI
( ). ASCII. He CGI . FTP
.

CGI-
, ,
URL CGI , :
http://www.myserver.com/cgi-bin/hello.pl
hello.pl , hello.cgi.
.
1. Hello, World.
2. .
CGI- - ,
CGI-.
CGI- . ,
. .
CGI- , , ! Web-, CGI- , . , , , CGI- .

17- . CGI

271

, CGI-


CGI-. , CGI-, ,
. CGI- .
, , , hello.cgi.
.

, ?
, CGI-.
Web-, CGI- .
CGI- , Perl.
.
perl hello.cgi
Perl :
(offline mode: enter name=value pairs on standard input)
, CGI .
18- , " ".
- , .
UNIX <Ctrl+D>, Windows <Ctrl+Z>. CGI- :
Content-Type: text/html
<B>Hello, World!</B>
Content-Type: text/html ,
HTML.
20- , " HTML- CGI". ,
header. - , CGI- . , CGI-, .

. .
. .

. Can't locate CGI.pin in @INC


. Perl.
CGI Perl. Perl
, " Perl".

272

III. CGI- Perl


, .
, Web-, .
. Not found 404 Not Found.
. .
URL. , https//
www.server.com/cgi/hello.cgi http://www.server.com/cgi-bin/
hello.cgi.
URL CGI.
. CG1 .

. .
. , Web- . .
CGI- , ,pl .cgi . ,
CGI-
.
URL . , URL.
. Web-, . Web-
CGI-, .
Web-, ,
. Web-.

. Forbidden 403 Error.


. CGf-. Web-, UNIX.
hello.cgi,
, , Is -1
hello.cgi. :
-rwxr-xr-x

I user

93 Aug 03 23:06 hello.cgi

-rwxr-xr-x.
, .

17- . CGI

273

Internal Server Error


500Error
Internal Server Error 500 Error, ,
CGI- - .'
.
, , . Web- . , CGI-.
. . UNIX

tail server_log
. Web- .
CGI-. FTP- Web-, , .
, .
Internal' Server Error . . .
. No such file or directory: exec of /cgi-bin/hello.cgi failed
.
#! . , Perl. FTP Perl Is dir.
CGI- FTP
ASCII-. FTP Windows UNIX .
CGI- UNIX .
(. Forbidden " ".)
. Can' t locate CGI. pm in @ INC
.
Perl ,
. Perl CGI, Perl. Perl . .
. Syntax error, warning, Global symbol requires, etc.
.
.
, " ,
?".

274

III. CGI- Perl

. Premature end of script headers.


.
, Content-Type,
- . ,
header CGI.
.
. .
, header ( ).
header .
CGI- header, "Content-Type: text/html\n\n" . ,
header , .
\\ -, header .
.
system ' '
header. ,
:
#I/usr/bin/perl -wT
use strict;
use CGI;

$|=1; #
print header;

CGI-. ,
Web-. .
CGI- , , .
CGI-, ,
.


CGI. ?
, . CG1 .
CGI. ,
Internet. 1- , " Peri", ,
" ". CGI
"", , .

17- . CGI

275

CGI Perl . .
, . ,
CGI. CGI.
cgi-lib.pl. CGI?
. cgi-lib.pl CGI. cgi-lib.pl .
CGI- Perl, , , TCL?
Perl CGI. .
1. Perl .
2. Perl ( )
CGI-.
3. Perl , , ,
CGI.
4. Perl .
, Perl CGI,

.lang.perl.misc?
comp.infosystems.www.authoring.cgi.
,
http://www.w3.org/CGI/.


1. CGI- :
) Perl, UNIX ;
) Perl;
) ,
.
2. Perl Web?
) ;
) .

1. ). Perl ,
CGI-,
2. ). Perl 1987 , a CERN Web 1991 .

276

III. CGI- Perl


CGI- "Hello, World!". localtime, HTML. He . , HTML Web-,
.

17- . CGI

277

18-


Internet HTML. , , , , . ,
Web-.
, Submit ( )?
CGI-.
, CGI- .
.
CGI- Perl.

CGI- .

CGI-.


, , ,
. ,
HTML.

HTML
, , .
HTML, , . CGI- HTML.
HTML, <HEAD>, <BODY> <DOCTYPE>,

.
. .

278

III. CGI- Perl

HTML HTML, . Web- HTML . , , , . Web- CGI- .


18,1 HTML .

18.1. HTML
1: <FORM action="http://www.server.com/cgi-bin/submit.cgi" method="get">
2: : <INPUT TYPE="text" name="name">
3: <BR>OnHcaHHe:
4: <BR><TEXTAREA name=>Idescription" rows=5 cols=40>
5: </TEXTAREA>
6: <INPUT type="radio" name="sex" value="male">Myi.
7: <INPUT type="radio" name="sex" value="female">JteH.
8: <BR>
9: <INPUT type="submit" value="3anpoc"><INPUT type="reset">
10:</F0RH>
. 18.1 Web- Internet Explorer 5.
E:\Books\Perl\Examplcs\fsll8J1 html - Microsoft Internet

0"

'AapecjCE\Books\Fexampies\isne_Oi html

jE:\Books\Per
",

: |

.fl]

, 18.1. , 18.1, Web-


Internet Explorer 5.
<FORM> HTML.
method ,
GET POST. , CGI GET.
. action URL CGI-, .
<INPUT> ,
. "name".
<TEXTAREA>
. name. "description".
HTML name,

18- .

279

. CGI- , name
.
,
. . .
name.
Submit.
CGI- . .
HTML 4,0 ,
. , , , rows cols
TEXTAREA . .
HTML 4.0,
, Web- http://www.w3c.org.

Submit?
Web- , .
Web-
(. !8.2). , name
. sex
. Web-.

FI0="HsaBOB"

<ISPUT TYPE=TEXT HAHE=FIO>

, 18.2.

, URL.
, URL CGI- (. 18.3).
Web-

, 18.3.

280

III. CGI- Peri

CGI-
: GET POST (. 18.4).
.
Web-

. 18.4.
CGI- ,
(. 18.5). HTML,
, URL CGI-.
Web-
10="

[
,
!

. 18.5. CGI- Web-

CGI-
CGI-, ,
, .
CGI param.
, , CGI-. CGI- , HTML-
18.1, param description, sex, name
submit.
param , .
, param ('sex') male female,
, .
18.2 CGI- .

18.2. CGI-
1:
2:
3:
4:
5:

jf!/usr/bin/perl -w
use strict;
use CGI gv(:standard);
print header;

18- .

281

6: print ": ", param('name'), "<BR>";


7: print ": ", param('sex'), "<BR>";
8: print ":<BR>", param('description'), "<P>*
, , ,
under.

GET POST
, 18.1, <FORM>
method. , Web- Web-. .
( , .. , <F0RM> method) GET.
CGI- URL. Internet URL:
http://www.server.com/cgi-bin7sample.pl?name=foosdesc=Basic%2QForms
CGI- URL .
param. He
. param , .
, POST, , . URL,
CGI- Web-.
, CGI . ,
param.
Internet CGI-, QUERY__STRIKG REQUEST_METHOD, ,

GET POST. CGI , , . .


, ? . GET Web- URL,
. , URL
http://www.server.com/cgi-bin/sample.pl?name=foobdesc=Basic%20Forms
. CGI sample.pl , .
CGI-. CGI- GET .
, , Web- , CGI- . ,
, URL GET .
POST URL , . ,
CGI-, .

282

III. CGI- Perl


Web
CGI- Web-, ,
, Web, .
HTML . CGI- Web-.
CGI- Web. ,
.


Web- HTML
(. 18.6). , , - .
Internet
Web-
: " ?

. 18.6.
, , CGI ,
Web-. (. 18.7)

Internet
.111 1 I y ^ggV

'

Web-
!"

: "

. 18.7,
,
. Internet .
,
, .
, CGI-.
.
( , ).
( , PIN-,
).

18- .

283

: Internet ,
.
"!" . " Internet , . , ". Web
. Web- . http, https.


,
CGI-, Perl ,
. Internet , ,
, , Web.
CGI- .
HTML CGI-, 18.3 18.4.

18.3.
1: <PORM action="/cgi-bin/directory.cgi">
2:
3:
4:
5:

?
<INPUT TYPE=text NAME=dirname>
<INPUT TYPE=subioit name=Bubmit value="">
</FORM>

18.4. CGI- directory.cgi


l:
2:
3:
4:
5:
6:
7:
8:

tl/usr/bin/perl -w
f HE ,
use s t r i c t ;
use CGI qw(:all);
print header;
my $directory=param{'dirname');
print ' I s -1 $directory~; I

18.3 ,
directory.cgi. directory.cgi Is -1, DOS dir. .

. CGI- ,
.

284

III. CGl- Perl

, $directory
! , dirname /home; cat /ets/passwd,
CGI-
Is -I /home; cat /etc/passwd
Web-. UNIX MSDOS. Web- , Internet.
Perl , . -,
, #!, (data tainting).
, ( ,
, ), . , open, system, , .
open, system ' ' ,
PATH.
18.5 directory.cgi.

18.5. directory.cgi
1: #!/usr/bin/perl -wT
2: f
3: use strict;
4: use CGI gw(:all);
5:
6: print header;
7: t
8: $ENV{PATH}='/bin:/usr/bin'
9: my $dir=param('dirname');
10: i ,
11: /home/projects
12: if ($dir=~m,"(/home/projects/[\w/]+)$, ) {
13: $dir=$l; I "" ,
14:
I . "perldoc perlsec"
15: print "Is -1 $dir';
16: }
Perl persec , Perl.


HTML/CGI .
HTML, 18.6.

18- .

285

18.6. HTML
1: <FORM action="/cgi-bin/doit.cgi">
2: , :
3: <INPUT TYPE=text length=15 name=color>
4: <IHPUT TYPE=submit value="3anpocH>
5: </FORM>
color 15 ,
? , . HTML , length
. ,
,
.
, ,
HTML, Java JavaScript. , color 15 , CGI Perl :
my $color=param{'color');

$color=substr($color, 0, 15); t 15


Web- , .
, . ,
Web - .
Web, CGI-.
. Web- .
CGI- - , , ,
.
CGI-.



Web-. HTML, , . , .
; , Web-.
18.7 HTML,
. , .

286

III. CGI- Perl

18.7.
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:

<FORM action='7cgi-bin/helpdesk.cgi H name="helpdeskH>


:
<INPUT TYPE=radio name=probtype value=hardware>

<INPUT TYPE=radio name=probtype value=software>

<BR>
<TEXTAREA name=problem rows=10 cols=40>
.
</TEXTAREA>
<BR>
Bane :
<INPUT TYPE=text width=40 name=name><BR>
<INPUT TYPE=submit name=submit value="3anpocH>
</FORM>

CGI- /cgi-bin/helpdesk.cgi.
18.8. - , URL , 18.7. *

18,8. CGI-
1: JM/usr/bin/perl -vT
2: use strict;
3: use CGI qw{:all);
4: use Fcntl qw(:flock);
5:
6: # .
7: my $gbdata=H/tmp/guestbook";
8: .
9: my $semaphore_file=H/tmp/helpdes}c.sem';
10:
11: J { )
12: sub get_lock {
13: open(SEM, ">$semaphore_file")
14:
|J die " : $!";
15: flockfSEM, LOCK_EX) || die " : $!";
16:}
17: i
18: sub release_lock {
19:
close(SEM);
20: }
21;
22: I
23: sub save {
24:
get_lock();
25:
open(GB, "$gbdata")
[| die " $gbdata: $!";
26:
print GB "name: ", param{'name'), "\n";
27:
print GB "type: ", param('probtype'), "\n";

18- .

287

28:
print GB "problem: ', param('problem'), "\n";
29:
close(GB);
30:
release lock{);
31:}
32: I
33: t HTML .
34: sub display {
35:
openfGB, $gbdata)
11 die " $gbdata: $1";
36:
while(<GB>){
37:
print "<B>$_</BXP>"; #
38:
my($type, $prob);
39:
$type=<GB>; f
40:
$prob=<GB>; # 3- ...
41:
print "$type<P>";
42:
print "$prob<BRXHR>";
43:
}
44:
close(GB);
45: }
46:
47: print header;
48: I 'submit' CGI-,
49:
50: I 'submit' 18,7
51: if (defined param('submit')) {
52:
save;
53:
display;
54:} else {
55:
display;
56:}
; 18.8 ,
' .
get_lock() releasej.ock().
,
CGI-. ,
helpdesc.cgi. . , , , .

288

CGI- . , 18.7,
.
.

III. CGl- Perl


HTML CGI.
, CGI- param CGI.
. CGI-
.
.


, .
CGI, 17- , " CGI". ,
, CGI-.
Internet , ,
$ENV{QUERY_STRISG}?
CGI . , ,
. , .
- # I,
Too l a t e for - option . ?
- , Perl . , ,
#!,
. ,
, -:
perl - -d foo.cgi
Perl CGI-? ?
CGI- . ,
, .


1. param ?
) undef;
) ;
) .

18- .

289

2. POST GET CGI?


) ;
) .
3. HTML- (
)?
) ;
) .

1. ). param
, CGI-.
2. ). .
3. ). . HTTP CGI
. .

CGI- .
.

display(} ,
. , .

290

III. CGI- Perl

19-

Web . . Web-, , , ..

, .
, .

Web- " "


CGI- . Web-
Web- . Web- , , . .
, Web-
. .

, ,
.
(, ), , , ,
.
, . ", , ", , , , .
: " ; -".
, ,
.

19- .

291

Web : / , Web "", . , HTML .


Web-
. HTML-. ,
, HTML-,
. HTML :
<INPUT type="hidden" name="fullname" value="Pink Floyd">
HTML- ,
("fullnarae") ("Pink Floyd") . CGI-, Perl,
.


, Web-
. ,
, .

Web-,
20- , " HTML- CGt-". ,
,
, HTML-. .

(. 19.1) .
, CGI-
. CGI- , . 19.2.
. ( ) CGI . ,
.
CGI- HTML-
, .

" ". , , "" CGI , .
,
, - , . 19.3.

292

III. CGl- Perl




;>

. 19.1.

. 19.2.

. 19.3.

,
HTML-. -,
. HTML- , Web- .
-, . , Web-
HTTP. .
. , CG1 "" .
, ,
.
, Web-
View^Page Source. ( Internet Explorer HTML.) ,
: ,
.

Internet . , , , , .
, . ,
. , .
1. , -.
.

19- .

293

2. , , .
3. , .
4. , ,
.
CGI-.
( ) , . 19.1.

use CGI:tCarp qw(fatalsToBrowser);
CGI- , Web, Web. CGI- .
, .
. CGI.

19.1. CGI",
1: ll/usr/bin/perl -w
2: use Fcntl qw(;flock);
3: use CGI gw(:all);
4: use CGI::Carp qw(fatalsToBrowser);
5: use strict;
6: my $eurveyfile="/tmp/survey.txt";
7: my survey answers=qw(pettype daytype clothes
8:
*~ castaway travel risky ownpet
9:
realname comments);
10: my $semaphore file="/tmp/survey.sem";
11: print header;"
12: if (1 param ) {
13:
14:
15:
16:
17:
18:
19:
20:

page_one();
I
} elsif (defined param('pageone')) {
page_two{);
# ,

} elsif (defined param('pagetwo')) {
page_three(); # .
} else {
survey_done(); I
)
i .
68. HTML-
. .
save() repeat hidden{).

294

III. CGI- Perl

1213. CGl- , ..
, page_one(), .
1417. CGI- HTML, pageone, page_two(). pagetwo, page_three().
19. CGI- HTML-,
pageone pagetwo, ,
.
survey_done{) , .
,
, . 19.4. CGI-
, , .
Web-

Web-

1.
2. CGl-

CGI-
0. pageone
pageone
.
3.

CGI -
\
pagetwo

,

/ CGII
6.
4. CGl-


Web-

5.
CGI-
pagethree

Web-

. 19,4. , HTML-
19.2 CGI- .

19.2. CGI-,
21: sub page one {
22:
printEND PAGE_0NE;
23: <FORM>
24: ?<BR>
25: <INPUT type=radio name=pettype value=dog>Co6aK<BR>
26: <INPUT type=radio name=pettype value=cat>Komex<BR>
19- .

295

27:
28:
29:
30:
31:
32:
33:
34:
35:

36:
37:
38:
39:
40:
41:
42:
43:
44:
45:

<>
?<BR>
<INPUT type=radio name=daytype value=early>K <>
<INPOT type=radio name=daytype value=late>K coBaM<BR>
<P>
, <BR>
<INPUT type=radio name=clothes value=casual>B <>
<INPDT type=radio name=clothes value=business>B <11>
<P>

,
?<BR>
<INPUT type=radio name=castaway 30: 1=.> TepKHH<BR>
<INPUT type=radio name=castaway 1=> <>
<INPUT type=radio name=castaway value=pof>poeccop<BR>
<IHPUT type-radio name=castaway value=skipper>KanaTaH KOpa6n<BR>
<INPUT type=submit name=pageone value="">
</FOftM>
END_PAGE_ONE
}
22~44 Perl,
. (inline document). , . , Perl,
, Perl, , .
, ,
.
, , , :
$a=END_OF_QUOTE;
.
END_OF_QUOTE
, ( END_OF_QUOTE, 19.2 END_PAGE_ONE),
.
" "
.
, ,
("")- , $ .
Perl
HTML-, , PRINT ..

, 19.2, HTML-. <FORM>


. CGI, . method,
GET.

296

III. CGI- Per!

, pageone. CGI- pageone;


.
CGI- .
CGI- 19.3.

19.3. CGI-,
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:

i
sub repeat_hidden {
foreach my $answer ( Gsurvey^answers ) {
if (defined param($answer)) {
print "<INPUT TYPE=hidden";
print " name=$answer ";
print " value=\"", param($answer),'\">\n";
}
}
}
sub page_two {
my $pet=param{'pettype');
if (! defined $pet) {
$pet="goldfish";
}

61:
62:

<FORM>

printEND_PAGE_TWO;

63: ..,<BR>
64: <INPUT type=radio name=travel value=travel>nyTenecTBOBaTb<BR>
65: <INPUT type=radio name=travel 1=>0 floua<BR>
66: <P>
67: ce6s...<BR>
68: <INPUT type=radio name=risky value=yes>Be3paccyflHHM<BR>
69: <INPDT type=radio name=risJcy 1=>0<>
70: <P>
71:
$pet?<BR>
72: <1 type=radio name=ownpet value=$pet>fla<BR>
73:
<INPUT type=radio name=ownpet value=no>HeT<BR>
74:
<P>
75:
<INPUT TYPE=submit name=pagetwo value="flanee">
76: END PAGEJTWO
77:
~ repeat_hidden();
78:
print "</F0RM>";
79: }
47. 46,

. survey__answers
"1=" HTML-. CGI- ,
.
4849. , survey_answers. , .
HTML <INPUT TYPE=hidden>.

19- .

297

5660. . ,
param( 'pettype') dog cat,
$pet. paramf 'pettype') , goldfish.

61~76. , $pet . ,
, .

77. HTML-
.
(
), , .
19.4.

19.4. CGI-,
80: sub page_three {
81:
printEND_PAGE_THREE;
82: <FORM>
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:

93:
94:
95:

! !<BR>
:
<IHPUT TYPE=text name='realname"><BR>
:<>
<TEXTAREA NAME=comments cols=40 rows=10>
</TEXTAREA>
<P>
<INPUT TYPE=submit name=pagethree
value="Submit survey results">
END_PAGEJTHREE

repeat hidden{);
print V/FORM>";
}

page_three :
. repeat_hidden(),
. CGI- 19.5.

19.5. CGI-,
96:
97:
98:
99:
100:
101:
102:
103:
104:
298

sub survey done {


save();

print "!";
}
*
f $surveyfile
*
sub save {
get lock();

HI. CGI- Perl

105:
open(5F, "$surveyfile")
106:
|| die " Ssurveyfile: $1";
107;
foreach my $answer {Gsurvey_answers) {
108:
if (defined param ($answer) ) {
109:
print SF $answer, "=", param($ansver), "\n";
110:
}
111:
}
112:
close(SF);
113:
release_lock();
114: }
115: IF
116: $ ,
117: ( .
118:
*
*
119:
120: t ( )
121: sub get_lock {
122:
open(SEM, ">$semaphore_file")
123:
|| die " : $!";
124:
flock(SEM, LOCK_EX) || die " : $1";
125: }
126:
127: I
128: sub release_lock {
129:
close(SEM);
130: }

'.

96.
. , . save().

103. save() save(),


18- , " ".
get_lock(), ,
repeatJiiddenO,
release_lock{).


. , .

, Web-, , .
, . , Web , ,
.

19- .

299


, , ?

, , , , -
.
Peri CGI-, HTML-. , HTML-
. <HEAD>, <HTML>, .. , . , Web , .
, ,
.
: Can't find string terminator "XXXX"
anywhere before EOF at
.
, , . :
print MARK;

HARK
MARK .
,
. MS-DOS Windows
. , .


1.
, :

Web-

) cookie;
) HTML-;
) HTML-, cookie
.
2. HTML <F0RM> action:
) ;

300

III. CGI- Perl

) CGI, ;
) .
3. CGI- . ?
) print EOP; 19.2 ;
) HTML- , <HEAD>;
) .

1. ), ).
cookie.
.
2. ).
. <F0RM> action, URL
, .. URL CGI-, .
3. ). print EOP; . )
, (.
"").

CGI-
. , , .

CGI-,
, , . :

/:

40%

45%

15%


:
?

20%

15%

30%

35%

40%

19- .

35%

301

20-
HTML CGI
, CGI-
Web- .
.

HTML- .

CGI- -, HTML-.
CGI-.

(SSI).

HTTP
17- , " CGI", ,
Web- ( Netscape Internet Explorer) Web (, Apache IIS) CGI. . , , CGI,
.
, .

, (Hypertext Transfer
Protocol HTTP). :
HTTP 1.0 HTTP 1.1 ( ).
, , internet, Request For Comments, RFC. , Internet Engineering Task Force (IETF), Web no
http://vww.ietf.org. HTTP RFC 1945 RFC2616. , .
302

III. CGI- Perl

Web- Web-, , :
GET http://testserver/ HTTP/1.0
Connection: Keep-Alive
Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, image/png, */*
Accept-Charset: iso-8859-1, *,utf-8
Accept-Encoding: gzip
Accept-Language: en, en-GB, de, fr, ja, ko, zh
Host: testserver:80
User-Agent: /4.51 [en]C-c32f404p
(WinNT; U)
GET , URL
.
1.0 HTTP.
Connection ,
.
, Web-. Keep-Alive , , .
Accept ,
. */* Accept ,
. (iso-8859-l ) ,
. AcceptEncoding: gzip , , ,
gzip (GNU Zip). , Accept-Language , :
(), (), , ..
Host , Web-. ( ) URL.
, Web- Mozilla/4.51 [en]Cc32f404p (WinNT; U). Web- (user agent).
, :
GET http://testserver/ ~> 200 OK
Date: Thu, 02 Sep 1999 19:54:39 GMT
Server: Netscape-Enterprise/3.5.1G
Content-Length: 2222
Content-Type: text/html
Last-Modified: Wed, 01 Sep 1999 17:12:03 GMT
, .
GET ,
Web-. 200 , "" .
" ",
Server: "" Web- NetscapeEnterprise/3.5.1G.
Content-Length , 2222 .
.
Content-Type . HTML-
text/html, image/jpeg.

20- . HTML- CGI-

303

Last-Modified "" ,
. Web-
-,
Internet.
, -.
, .

:
Web- . CGI-, ,
Web- .
, 7/#-. Telnet- , UNIX. HTTP.
UNIX, telnet. Microsoft Windows, telnet TCP/IP.
Telnet-, . telnet Macintosh,
Telnet- Internet .
Web- telnet :
$ telnet www.webserver.com 80
www.webserver.com Web-, 80 , ( Web- HTTP). telnet ,
, , .
Telnet-
. :
. HTTP , "" , . UNIX
, :
Trying www.webserver.com
Connected to www.webserver.com
Escape character is ' * ] '
(Windows Macintosh),
.
:

GET http://www.webserver.com/ /1.0


<Enter> . Web-
HTTP- Web, .

:
CGI- HTML-.
CGI- , .

304

III. CGI- Pert

header CGl- ,
. MIME Content-Type, , . "",
.
header Content-Type
text/html. "", , HTML.
, .
, , (browser plug-in)
, .
header ,
text/html, -type:
print header {-type => TnnjflME);
MIME, Content-Type,
, text/plain ( , ), image/gif image/ jpeg ( GIF- JPEG-),
application/ ( ,
). - MIME Content-Type
application/octet-steam, , .
,
Web-, " " Web-.
Web- . , " "?
, HTML-
CGI- Perl, .
HTML- Web-:
<Body>
:
<IMG SRC="/cgi-bin/daily_image.cgi">
</Body>
HTML- ,
<IMG> CG1-, GIF- JPEG-. , .
, , . jpeg.
,
GIF.
CGI- daily_image.cgi , 20.1.

20.1. , " "


1
2:
3:
4:
5:
6:
7:

H/usr/bin/perl -w
use s t r i c t ;
use CGI qw(:all);
my($imagedir, $day, 8jpegs, $error);
$inagedir="/web/htdocs/pic_of_day";

20- . HTML- CGI-

305

8: $error="/web/htdocs/images/error.jpg";
9:
10: sub display_image {
11:
my($image)=|j ;
12:
open(IMAGE,v$image") || exit;
13:
binmode STDOUT;.binmode IMAGE;
14:
print <IMAGE>;
15:
close(IMAGE);
16:
exit;
17: }
18:
19: print header(-type => 'image/jpeg');
20:
21: * , 1-28, 29, 30 31
22: $day=(localtime)[3];
23: $day=$day-l; # 0-27, ....
24:
25: opendir(IMGDIR, $imagedir) || display_image{$error);
26: jpegs=sort grep(/\.jpg$/, readdir IMGDIR);
27: closedir{IMGDIR);
28:
29: my $image="$imagedir/$jpegs[$day]";
30: $iraage=$error if (not defined $jpegs[$day]);
31: display image($image);
. : :/ .
7. ,
. , .
8. , , CGI- HTML-, , ,
. Simagedir ,
. jpg-, Serror.

306

1016. , . Windows- STDOUT , , . jpg STDOUT . ,


STDOUT IMAGE , binmode.
UNIX
binmode, . 12: ,
, .

19. HTML-, , Content-Type text/html image/jpeg.

25. .
, display_image{), Serror .

tit. CGI- Perl

26. , . readdir. . jpg. , jpegs.

CGI-
CGI-.
URL
. , CGI- time.cgi,
:

< BREF="http://server/cgi-bin/time.cgi "> </>


Web- CGI- time.cgi
, .. Web-.
CGI-, ,
17- , " CGI".
CGI- HTML. , CGI- process.cgi
Submit:
<FORM METHOD=GET ACTION="/cgi-bin/process.cgi">
<IHPUT TYPE=TEXT NAME=STUFFXBR>
<IHPUT TYPE=SUBMIT>
</F0RM>

CGI- : CGI- . ,
.

CGI-
CGI-
. , , CGI- foo.cgi
X Y, . < HREF>
URL . URL . 20.1.

http://www.foo.cora/cgi~bin/prog.cgi?name=Ringo&jobdriraiiner

CGI-

. 20.1. URL
, CGI- ( HTML-). , . -

20- . HTML- CGI-

307

, , CGI sign year, 1969 , HTML-:


< HREF="http://www.server.com/cgi-bin/astrology.cgi?sign=OBeH&
=1969">, </>
CGI- param CGI
:
*!/user/bin/perl -w
use CGI qw{:all);
use strict;
print header;

print " ", param('year'), " ",


param('sign'), " , - .\";
. ( ), , , author :

< HREF="http://www.server.com/cgi-bin/book.cgi?author=s
title=Beowolf">Beowolf</A>


CGI-
, URL. , ? (
) URL .
, &, .
Internet
RFC 2396.
URL, . , ASCII-
, . ""
", !" 1:
!2%20!
, "" , , . CGI , .
, URL "" ;
* . URL , . . .

308

III. CGI- Perl

jfl/user/bin/perl -w

use strict;
f 'escape'
use CGI qv(:all escape);
print header;
my $string="npHBeT, 1";
print '<A HREF="http://www.server.com/cgi-bin/parrot.cgi?message=',
escape{$string) , '"> </>';
( URL) HTML-. ,
CGI: use CGI qw(:all escape). CGI escape
,
use .
URL- :
#!/user/bin/perl -w
use strict;
use CGI qw{:all escape);
my %books=( Insomnia => 'S. King', Nutshell => 'O\'Reilly');

$ URL
my $url="http://www.server.com/cgi-bin/add_books.cgi?;

I URL "."
foreach my $title (keys *books) {
$url .= escape($title); t
$url .= "=";
$url .= escape{$books{$title}); #
$url.="&";
print header;
print "<A HREF=$url>flo6aBHTb </>';
URL :
http://www.server.com/cgibin/add_books.cgi?Insomnia=S.%20KingfcNutshell=0%27Reillyfc
& URL CGI-
param.

Web-
Web- , . Web-,
. Web-,
. , , , , ,

20- . HTML- CGI-

309

, , .

.
, Web- , (server-side
includes SSI),
(server-parsed HTML). Web-
HTML Web-, , Web- (. 20.2). Web-
, ,
"" CGI-.
Web-

Web- SSI

. 20.2. Web-
HTML-
Web- SSI.
"" HTML- SSI-,
, , HTML- .shtral .stm. Web- , , SSI
, .
Web- HTML-
, . , <!--iecho var="LAST_HODIFIED"--> Web- Apache
HTML-.
"", . , .
.
Web-

Web-

<HTML>

<HTML>

<BODY>

<B0DY>

<!~fecho var=HLAST_MODIFIED"~>

Wednesday, Ol-Jul-2000 21:29:31 EDT

</BODY>

</B0DY>

</HTML>

</HTML>

310

III. CGI- Peri

SSI Web- -. , . Web-


SSI, Personal Web Server Microsoft.
SSI, ,
Web- ( '), Apache
Internet Information Server Microsoft.
, SSI,
Web-.
SSI lexec, HTML-
:
<!lexec cgi="/cgi-bin/stockprice.cgi">

texec,
Web-

CGI-
stockprice.cgi. CGI- HTML,, . CGI- HTML- ( #)
.

: SSI
, ",
!", , .
: , (. 20.3),

4
1
1
day.jpg

night.jpg

. 20.3, : day.jpg night.jpg


HTML- (. ).
, , , , .shtml .stm, Web- SSI.
<BTHL>
<HEAD>
<1> </1>
</HEAD>
<BODY>
Web-. :
<!--texec cgi="/cgi-bin/sunmoon.cgi">
</BODY>
</HTKL>
sunmoon.cgi 20.2.

20- . HTML- CGI-

311

20.2. ,
1: #!/usr/bin/perl -w
2:
3: use CGI qw(:all);
4:
5: I 24- localtime().
6: my $hour=(localtime)[2];
7: my $image;
8:
9: # , -
10: if ($hour<6 or $hour>18) {
11:
$image="night.jpg";
12: } else {
13:
$image="day.jpg";
14: }
15: print header;
16: print qq{<IMG SRC="$image" ALT="$image">\n};
; .

3. CGI-,
CGI. /{:11)
.

6. localtime , ( 4-
, " : "). localtime , [2] ,
( ) $hour.
24- .

15. , HTTP, - header CGI, , ,


, Web- .

16. <IMG>, ,
$day, $nignt, ALT , .
Web-, 8 ,
:
<HTML>
<HEAD>
<1> </1>
</HEAD>
<BODY>
Web-. :
<IMG SRC="day.jpg" ALT="day.jpg">
</BODY>
</HTML>

312

III. CGI- Perl


CGI
( header), ,
CGI- ( escape param). CGI ,
. . 20.1,
CGI,
, perldoc CGI.
,
Web- Web-
HTTP. , Web (, referer user_agent), Web-
(, server name).

20.1.

referer

URL ,
. (, . Internet, , , .)

user_agent

, Web-,
(, Netscape, IE Lynx)

remotejmst

(host), IP- , . ,
Web- (hostname)

scriptjiame

CGI- URL (,

serverjiante

, CGI-

virtualhost

Web-,
CGI-.
serverjiame,
Web-. v i r t u a l j i o s t ,

/cgi-bin/foo.cgi)


:
$i/usr/bin/perl -w
use strict;
use CGI qw(:all};
print header;

20- . HTML- CGI-

313

print " : ", referer, "<BR>";


print " : ",
user_agent, "<BR>";
print " : ", remote_host,
"<BR>";
print " : ",
scriptjiame, "<BR>";
print " : ",
server_name, "<BR>";
print " : ",
v i r t u a l j i o s t , "<BR>";
Web-
:
: http://testsyB.net/links.htinl

: Hozilla/4.51 [en] (Win95; I)


: 192.168.1.2
: /cgi/showstuff.cgi
: testsys
: perlbook

, CGI-, , HTTP- (redirection). , , CGI- .


, ,
, . , , , (plug-in) Netscape Windows.
Web-,
.
URL CGI- (. 20.4).
Web-
1.

Web-
3.

2. CGI-

. 20.4. Web-

314

III. CGI- Perl

CGI
redirect, HTTP- .
20.3 , Netscape Windows , .

20.3.
1:
2:
3:
4:
5:
6:

7;
8:
9:
10:
11:
12:
13:
14:
15:
16:

JH/usr/bin/perl -w
use CGI qw(:all);
use s t r i c t ;
my($browser, $target);


$browser=user_agent;
$target="http://www.server.com/generic.html";
i WinXX Netscape
if ($browser="/Hozilla/ and $browser="/Win/) {
$target="http://www.server.com/netscape.html";
}
print redirect( -uri => $target );
.

9. $browser .
10. URL $target. , Netscape, .

1314. , $browser, Mozilla Win,


.

16. .

CGI , (, JavaScript- HTML-) . JavaScript ,


window.location.href JavaScript URL .
HTML <META HTTP-EQUIV=>lrefresh">
,
.
JavaScript "" . HTTP
CGI- ,
HTML- .
Netscape user_agent CGI
Mozilla. Web Mosaic. , Windows 95 Netscape
4.51 user agent, Mozilla/4.51 - (Win95; I).

20- . HTML- CGI-

315


, , Web- , HTTP. , CGI- ,
SSI . , HTTP .


, , SSI, .

SSI . -,
, Web- SSI. -, ,
SSI Web- " ", ..
. -, , HTML-
, SSI. ,
, .
, ,
HTML, SSI.
<!~# cgi-->, , CGI ( SSI).
Web-, , -
, SSI .
HTML- SS1, ,
.
, Telnet-?

telnet , , Web- ,
80. ,
telnet.
. Telnet-
, . : . GET <Enter>.


1. URL ?
< HREF="/cgi/foo.pl?name=Ben FranklinfiJob=printer">
) ;
) , CGI-;
) , Ben Franklin .

316

III. CGI- Perl

2. (server-side
includes)?
) ;
) Web-;
) .

1. ).
"" .
2. ). Web- SSI (
HTML-) , .

telnet Web- .

20- . HTML- CGI-

317

21-
cookie
19- , " ", ,
HTML- Web- "" Web-. , CGI- ,
.
, ,
, .
cookie, , CGI- HTTP-. cookie .
.
cookie.

cookie.

, cookie.

cookie
cookie . .
, .
, , , , ,
, . ( ) .
cookie , CGI- ""
.
CGI-. cookie

318

III. CGI- Perl

HMTL-. cookie
: Web-, Web-, ..
cookie , CGI- cookie (. 21.1), cookie.
cookie CGI-,
, ,
. 21.2.
Web-cepeep

Web-

. 21.1. cookie CGI

Web-

Web-

. 21.2. cookie

cookie?
cookie . ( ),
cookie . cookie
magic cookies ( cookie), ,
. CGI-cookie .

cookie
cookie CGI
cookie. :
$cookie_object=cookie{ -name => 1_,
-value => cookie_,
-expires => ^,
-path => __,

#
#
-domain => __, \
-secure => true/false

cookie .
cookie . Perl ,
: .
cookie
cookie ( ). header CGI, cookie . cookie -value. -name cookie ,
, .
expires, -path, -domain -secure .

21- . cookie

319

header CGI cookie . , , cookie, header. He -


, cookie .
cookie , CGI, :
#l/usr/bin/perl -w
use CGI qw(:all);
use strict;
my $cookie=cookie(-name => 'Sample',

-value => ' cookie ');


i cookie
print header(-cookie => $cookie};
cookie
Sample . cookie
cookie .
, cookie . cookie, (. " cookie" ).
cookie CGI-
cookie. ( ),
cookie, :

(!cookie_list=cookie(); f cookie

i cookie
$cookie_value=cookie{$cookie_name);
cookie CGI, , .. ,
cookie, .
cookie Sample, CGI-:
|!/usr/bin/perl -wT
use CGI qw{:all);
use s t r i c t ;
print headerf);

print " cookie 'Sample': ", cookie{'Sample'), "<P>";


cookie cookie, . .
cookie . cookie Sample . "" cookie " cookie" .

320

III. CGI- Perl


cookie. Netscape Preferences Advanced. Internet Explorer
(Advanced)
{Internet Options) , cookie.

: cookie
,
Web- .
, .
1. , ,
.
2. cookie .
3. .
4. CGI-, .
Web- 21.1.

21.1. ColorChanger
1:
2:
3:
4:
5:

t!/usr/bin/perl -w
use strict;
use CGI qv(:all};
use CGI::Carp qw(fatalsToBrowser);
ny($requested_color, $old_color, $color_cookie)=("","");

6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
2"2:
23:
24:
2 5:
26:
27:
28:
29:
30:
31:

$old_color='blue"; I
I ?
if {defined param{'color')) {
$requested_color=param{'color');
}
I ?
if {defined cookie('bgcolor')) {
$old_color=cookie('bgcolor');
}
if ($requested_color and ($old_color ne $requested_color)) {
i cookie
$color_cookie=cookie(-name => 'bgcolor',
-value => $requested_color);
print header{-cookie => $color_cookie);
} else {
i , cookie
$requested_color=$old_color;
print header;
}
printEND_OF_HTHL;
<HTHL>
<BEAD>
<11,> </11.>
</BEAD>
<BODY BGCOLOR="$requested1color">
<FORM>

21- . cookie

321

32: <SELECT NAME="color">


33:
<OPTION value='red'>KpacHui
34:

35:
36:
37:
38:
39:
40:
41:
42:

<OPTIOS 1=''>

<OPTIOH 1='11'>
<OPTION value='white' >
</SELECT>
<INPUT TYPE=SUBMIT 1,=" ->
</FORM>
</BODY>
</HTML>
END OF HTML

| | ; ! ^ 1 .
710. CGI-
HTML-, param( 'color') . $requested_color .
1214.
cookie bgcolor ( !). , ( , cookie ) $old_color.
1519. ( cookie
), cookie .
2024. , cookie. ,
cookie .
2542. HTML.
30
HTML-.

: cookie
cookie, 21.2, CGI-,
cookie. cookie, Web-, Web-.

21.2. cookie
1: #!/usr/bin/perl -w
2:
3: use strict;
4: use CGI qv(:all);
5:
6: print header{);
7:
8: print " cookie, :<>";
9:
10: foreach my $cookie (cookie()} {
11:
print " cookie: $cookie <BR>";
12:
print qq{3Ha4eHfle cookie: "}, cookie($cookie}, qq{"<P><HR>};
: >

322

III. CGI- Perl

.
10. cookie
cookie $cookie.
11~12. cookie.


cookie cookie(),
cookie.


cookie
cookie .
cookie, . , , . , ( ) cookie, . cookie . ,
URL. (
.)

cookie
cookie : , cookie .
cookie HTML- .
cookie, , .

cookie ( , ).
CGi Perl .
cookie,
-expires. ,
cookie. ,
. 21.1.

21.1. cookie

+30s

30

+15

15

+12h

12

+6

+1

21- . cookie

323

. 21.1

now

cookie

-10m

cookie

Saturday,
28-Aug-2000 22:51:05 EEST

,
. 21.1. ,
. (
"" ) .
cookie, :
#l/usr/bin/perl -v
use CGI qw(:all);
use strict;
my $cookie=cookie(-name => 'Favorite',

-value => ' ',


-expires => '+8d' );

t cookie
print header(-cookie => $cookie);


.
cookie. , CGI-
cookie, , ( ) , .
, " cookie"
cookie. ,
, cookie .
cookie,
, ,
.
cookie .
cookie.
, cookie
" ". cookie . , cookie
, , .
, cookie
. , , , cookie, , .
, ,
Web-, , .

324

III. CGI- Perl

, , ,
cookie , . Netscape cookie cookies.txt, , . Internet Explorer cookie \Windows\Cookies.

cookie
cookie ,
. cookie " "
, . ,
Web- congo.com, .
Web-: www.congo.com shopping.congo.com (. 21.3). Web ( www.congo.com) ,
, , .
Web- www.congo.com HTML-
CGI-.
, . ,
www.congo.com, , . cookie, www.congo.com (. 21.4).
Web-

cookie,

wwv.congo.com

Web-

Web-

wvw.congo.com

Web-

Web-

shopping.congo.

. 21.3. Web-,

www.congo.con

shopping.Congo.

. 21.4. cookie

Web-,

, , www.congo.com
shopping.congo.com, cookie
shopping.congo.com. cookie , . cookie
www.congo.com, shopping.congo.com.
?
cookie shopping.congo.com.
. cookie . , www.congo.com cookie,
, Web- congo.com, . 21.5.

21- . cookie

325

Web-

cookie,

www.congo.con

Web-

Web-

shopping.congo.com

www.foo.com

www.congo.com

. 21.5. cookie,
Web-
cookie
-domain cookie:

$cookie=cookie( - => 'preferences',


-value => 'mysteries, horror',
-domain => 'congo.com'};
print header(-cookie => $cookie);
cookie preferences, congo.com.
cookie Web-, congo.com.
.
, .. .com
.net. ,
cookie .

cookie
cookie CGI. cookie URL, URL, CGI-. , , Web-, . 21.6.

-
ICGI-
( cgi-sales)
-
ICGI-
( cgi-engineering)

. 21.6. Web-, :

326

III. CGI- Perl

CGI-, ,
CGI- . CGI- cookie, CGI, . , , , CGI-, ,
cookie.
, -path cookie.
( URL ),
cookie . , cookie, CGI-,
:
i Cookie CGI-
$cookie=cookie{ -name => ' p r o f i l e ' ,
-value => ',,',
-path => ' / c g i - s a l e s ' ) ;
print header(-cookie => $cookie);
cookie ,
-path=>7'. " "
cookie, .. CGI-, -path
URL CGI-.
I cookie
$cookie=cookie( -name => ' p r o f i l e ' ,
-value => ',,',
-path => script_name{) J;
print header(-cookie => $cookie);
, script_name
CGI URL CGI-.
cookie, ,
cookie .

cookie
cookie . -secure cookie, cookie , . . cookie, , .
I !
$cookie=cookie( -name => 'account',
-value => '00-12-3-122-1313',
-secure => 1);
print header(-cookie => $cookie);
cookie cookie.
cookie ,
cookie .
f .
$account number=cookie{'account');

21- . cookie

327


.
. , Web-
cookie. He , cookie, ,
( ) , .

cookie
cookie ,
, .
""
Web- CGI-, cookie.
, cookie , , cookie ,
, , " ".

cookie
, cookie . , .
cookie, ,
"", - .
cookie -expire,
, .

cookie
, cookie. Internet,
HTTP- Web-, ,
cookie.
,
cookie ( ). , Netscape ( 1.1), Internet Explorer ( ), Lynx, Opera Web-,
cookie.
cookie.
user_agent CGI ,
cookie, .

cookie
, : ""
cookie?
Web- .
, Web- , . ,
, .
: .
, , Internet- . ( ) cookie
.

328

III. CGI- Perl

cookie Web- , .
,
.
, ,
(congo.com), , ""
,
.
. , , . -, ,
Web-. -
Web- (,
, Web-, congo.com), "" Web- ,
. , -
cookie, ,
Web-.
. "", Web-
Web- ""
"", .. Web- "" .
, , cookie .
cookie Web-.
cookie "" Web-,
. Web-, cookie,
,
cookie . ,
cookie, , . Web- ,
,
cookie.
, , cookie
, , ,
" ".

cookie ,
CGI-. , cookie ""
Web-, URL. ,
"" , cookie, , .

21- . cookie

329


cookie ?

cookie , - ,
:
$cookie=cookie(-name => 'preferences',
-value => 'bgcolor=blue,fgcolor=red,banners=no,java=no');
, cookie, split:
$cookie=cookie('preferences');
Goptions=split(/,/, $cookie);

I .
I '='
foreach $option (ioptions) {
($key,$value)=split(/=/, $option)
$Options{$key}=$value;
}

cookie , Web ?

, ,
cookie . .
1. < HREF> , CGI-, target URL:

< HREF="http://server/cgi/redirect.pl?target=http://www.congo.com">
Congo</A>
2. redirect.pl URL
(http://www.congo.com) target
param CGI:
$target_url=param('target');
3. cookie, URL. cookie
, cookie ( tracker):
$tracking_cookie=cookie(-name
=> 'tracker',
-value => $target_url,
-expires => '+lw');
4. redirect URL cookie:
print redirect(-uri => $target_url,
-cookie => $tracking_cookie);
, Web-, CGI-
cookie tracker, URL,
.

330

III. CGI- Perl

cookie Web-?

. redirect CGI ( header)


-cookie:
my $cookie=cookie(-name => 'target',

-value => ' foo.html');


print redirect(-uri => "http://www.server.com/foo.html",
-cookie => $cookie);


1. cookie
?
) cookie;
) cookie ;
) cookie .
2. -expire cookie,
cookie ,
?
) +7d;
) +lw;
) +10080.
3. cookie
?
) cookie
Web-, ;
) cookie ;
) cookie , .

1. .
2. ), ). +lw .
3. .

CGI-,
. ,
Web- <IMG>.

21- . cookie

331

22-

CGI
, Web, , .
, , .
, Perl- ,
Web-,
.
.
.

Internet.

UNIX
.

Web- .


Internet
Perl, , Internet.
Perl, Web (.. ""
NCSA) , , UNIX-to-UNIX copy (UUCP).
, ""
, , "" . "" "" , , (. 22.1)-

332

III. CGI- Perl

UUCP-
UUCP-
UUCP- UUCP-

. 22.1.
(store and forward).
UUCP ,
- .
""
, , ,
, .
.
(Simple Mail Transport Protocol SMTP), (. 22.2).

(Post Office Protocol POP), Internet (Internet
Message Access Protocol IMAP). SMTP.

SMTP

SMTP

. 22.2.


, (Mail Transport
Agent, ) , SMTP.
.
,
.
.
. - UNIX sendmail. sendmail , .
UNIX, :
$ /bin/echo "Subject:Test\n\nlIpHBeT, !" | sendmail fooebar.com
foo@bar.com.
sendmail : , ..

22- . CGI-

333

Microsoft Windows Macintosh . , Perl .


Net::SMTP , , SMTP. Internet "Mail Host", SMTP. -:
.
, . ,
, SMTP-, .
: , SMTP,
SMTP-
.
SMTP- , . ,
(Internet service provider ISP). ,
Web-, SMTP-
Web- . , .


sendjnail, Perl-. . -
. : . ,
, .
?
" ", , Perl-
.
(, ) . .

334


.
Internet.
.
, . ,
, Internet.
, , . .

III. CGI- Perl

( ). -, . ,
. -, ,
, . - , aol.com, hotmail.com,
. , ,
.
From:
Reply To: . Perl , , . , ,
.

.
, , .


.
(mailbombing) , , .

" ",
.
Internet / , .
, , , , , , .
: , - , , .
Internet . ,
,
. ,
.



Perl ,
CGI- . : , (, sendmail),

22- . CGI-

335

SMTP . ,
.

UNIX
UNIX
sendmail ( !), , .
- ( UNIX
sendmail) , . , 22.1, , .
UNIX, , " UNIX". - .

22.1. send mail


1: f {sendmail)
2: sub sendjnail {
3:
my($to, $from, $subject, f!body)=G_;
4:
5:
l
:
my $sendmail="/usr/lib/sendaail -t -oi -odq";
7:
8:
open(HAIL, "|$sendmail") ||
die " sendmail: $!";
9:
print MAILEND_OF_HEADER;
10: From: $from
11: To: $to
12: Subject: $subject
13:
14: END_OF_BEADER
15:
foreach (Gbody) {
16:
print MAIL "$_\n";
17:
}
18:
close(HAIL);
19: \
.

336

. Ssendmail
sendmail . ,
sendmail
.

8.
sendmail, Ssendmail. MAIL.

III. CGI- Perl

9~14. MAIL.

1517. MAIL.
\.
, :
(!<1=(", I", "!*);
send_mail('president9vhitehouse.gov', 'ovneregeeksalad.org',
'Taxes', Cbody);
, sendmail . , , " UNIX",
UNIX.
$sendmail sendraail . , /usr/lib, /usr/sbin /lib, .
whereis sendmail.
- , ,
.
, , , mail pine.
, , sendmail . , , .
22.1 sendmail , .
-t

(Prom, To, Subject ..) , .

-oi

, ,
.
.

-odq

sendmail ,
. . ,
. - -odq.

send_mail{) " ".

UNIX
Windows ,
- sendmail, . , Perl . .
: Perl Net::SMTP, ,
Perl-. , .

22- . CGI-

337

: Perl.
, . Net::SMTP libnet,
, . libnet
-.
" Perl"
Perl , UNIX, Windows
Macintosh. ,
,
.
sendjnail 22.2.
() , . .

22.2. sendjnail
1: I
2: sub send_mail {
3:
my($to, $from, $subject, body)=(!_;
4:
5:
use Net::SMTP;
6:
7:
j[ ,
8:
t
9:
my $relay="relayhost.yourisp.com";
10: $smtp = Net::SHTP->new($relay);
11: die " : $1" if (I defined $smtp);
12:
13:
$smtp->mail{$from);
14: $smtp->to($to);
15:
16:
$smtp->data(};
17:
18:
19:
20:
21:
22:
23:

$smtp->datasend("To: $to\n");
$smtp->datasend("From: $from\nn);
$smtp->datasend("Subject: $subject\n");
$smtp->datasend("\n");
foreach(body} {
Samtp->datasend("$_\n");
}

24: $smtp->dataend(J; I : "s"


25:
$smtp->quit;
26: >
.

338

5. Net::SMTP, .

10. Net::SMTP, , 9.

III. CGI- Perl

1323.
. .
Net: :SMTP, .
, , :
gbody={", !", "1");
sendjnail('presidentdwhitehouse.gov, 'ovnerGgeeksalad.org',
'Taxes', dbody);
, , Ssratp = Net: :SMTP->new($relay).
, . ,
("") , .
$smtp , .
, ,
.
"" $smtp->mail($from).
-> , , , .
mail , $smtp,
.
Net::SMTP . , Net: :SMTP.
$smtp->mail(addr). mail , . " " .
$smtp->to(addr). to , .
to
.
, , :.
$smtp->data(). data , ,
$smtp->datasend(data). . (:, From:
..), , Date: Received:, . :
$smtp->datasend("\n"). ,
$smtp->datasend().
$smtp->dataend(). dataend ,
. ,
.
Ssmtp->quit(). SMTP-.

Web-
send_mail(},
"" Web- !

22- . CGI-

339

CGI-, "" .
HTML-, , 22.3. ,
"" .

22.3. HTML-
1: <1 /cgi-bin/mailer.cgi>
2: <FORM METHOD=POST ACTION="/cgi-bin/mailer.cgi">
3: : <INPUT TYPE=text NAME=return_addr><BR>
4: : <INPOT TYPE=text NAME=subject><BR>
5: <BR>
: :<BR>
7: <TEXTAREA NAME=body ROWS=20 COLS=60 WRAP=hard>
8:
9: </TEXTAREA>
10: <BR>
11: <INPUT TYPE=SOBMIT VALUE="
12: </FORM>
CGI- . :

/bin/perl -v
use strict;
use CGI qv(:all);
use CGI::Carp qw{fatalsToBrowser);
#
send mail
I 22.1 22.2!
f
print header;
my $return=param("return_addr");
if (! defined $return or ! {return) {
print " e-mail<P>";
exit;
}
my $subject=param("subject");
if (! define $subject or ! {subject) {
print " <>";
exit;
}
t
t
send_mail('webmaster9mybost.com',
param($return),
param($subject),
param("body"));
print " .";
.
-, ,
sendmail, 22.1, 22.2.

340

III. CGI- Perl

, . -, , , :, ""
webmaster@myhost.com. , . ,
, :
Web-. - " ", , , .
.
, , Web-,
. :
<INPDT TYPE=radio NAME=target Value=l >
<INPUT TYPE=radio NAME=target 1=2>0
<INPUT TYPE=radio NAME=target 1=3>
CGI- :
$iormtarget=param('target');
%targets=( 1=> 'supportemyhost.com',
2=> 'salesGmyhost.com',
3=> 'legaiemyhost.com'};
if {exists($targets{$formtarget})) {
$target=$targets{$formtarget};
} else {
$target='webmastermyhost.com';
}
print $target;
,
Web- :. CGI - (
1-3), . , else ( ).


, , CGl- ,
, . : !
.
" " Internet
, . : !
, . 22.1
22.2, .
. , , .. " " . , , " ".
, ,
, , .
Internet RFC 822 . , -

22- . CGI-

341

RFC-822 , , , .
,
, . , /"[\v,]+\@([\w,-]\.)+\w+$/ . , me@somewhere.com. "" :
*qz.az
clintp!sol2!westwoodGdec.net
relay%mehost.com
"barney&fred"0flintstones.net
. , ,
RFC-822, 4 700 ,
.
,
Internet.
?

. -
- , ,
. , ,
.

,
Web-. send_mail(),
Perl- .
Internet .

, .
. , remote_host CGI, ,
. remotejiser (
Web-), ,
. , ""
,
Netscape Internet Explorer .
, , Web- , , Internet-, .

342

III. CGI- Perl

. ,
( at), .
{, postmaster, root) .
CGI-
From nobody... ?
, . sendraail .
"" Web-. Web- (ID) nobody, Web, httpd (
!) root - .
.
From:, .
?

MIME-, CPAN.


1. $foo=Net: :SMTP->new( 'mailhost')?
( , "
UNIX", , , .)
) ;
) , $foo,
SMTP-;
) Net: :SHTP.
2. () ?
) foo!bar!baz!quux.
) " "9bar.com.
) stuff%junk!"Wowzers"!foo.com!blat.

1. ).
), , Perl 4.
) ,
use Net::SMTP.
2. .
.

22- . CGI-

343

344

CGI- .
- .
( ,
Web-). ,
.

""
. , 19- , " ",
( )
( )
CGI- .

III. CGI- Perl

23-
Push-

Web-

CGI-. Web-
.
.

push- Web-.

Web-.

proxy- -.

push-
Web- . ,
.
Web-, CGI-, . , ,
, .
-, - CGI-.
90 , , ,
.
-, CGI- :
" 10% ", : " 20% " .. , ,
(- ),
Web-.

23- . Push- Web-

345.

, , ,
Web-, (. 23.1).

. 23.1. , Web-
push- {server push), ,
,
, .
Internet Explorer Microsoft
, push- . , Web-. Web-, Internet Explorer , push-, ,
(client pull).



Web- ,
. CGI , . CGI- " " . Web- CGI-, ( 500!). CGI- , . 23.2.
Web-

Web-

. 23.2.
346

III. CGI- Perl

CGI- "" Web-. , , Web-


Apache, , CGI-
nph-. , push.cgi CGI-
, nph-push.cgi CGI-
. Web- CGI-.
Internet Information Server (IIS) Microsoft
CGI- ; header
CGI . Web- I IS
.
, CGI- ,
Web- .

:
, Web-.
, 5
. Web-
, ""
(Stop), .
CGI , . Web-, , (multipart documents).
23.1 CGI- . , Web CGI- (.
).

23.1. CGI-
1: #!/usr/bin/perl -w
2:
3: use strict;
4: use CGI gw(:push -nph);
5:
6: $|=1; f
7:
8: print multipart_init;
9: while(l} {
10:
print multipart_start;
11:
print " <H1>", scalar{localtime), "</Hl>\n";
12:
print multipart_end;
13:
sleep 5;
14: }
.

4. CGI- , . , :push CGI. ,


CGI -nph.

23- . Push- Web-

347

8. multipart_init ,
Web-.
header Web-.

9. while(l) while,
.

10. multipartstart . ,
.

11. .
4- , " :
", localtime "Sun Sep 5 15:15:30 1999".

12. multipart_end .
multipart_start
.
, raultipart_init raultipart_end while.
: .

:

( 23.2), , /images. .
,
"" .

23.2.

1: #l/usr/bin/perl -w
2:
3: use strict;
4: use CGI qv{:push -nph);
5: my($imagedir, GJPEGS);
6: \
7: $imagedir="/web/Clinton TeBt_Area/images";
8: opendir(ID, $imagedir) J| die " $imagedir: $1";
9: f!JPEGS=sort grep{/\.jpg$/, readdir ID);
10: closedir{ID};
11:
12: $[=1; t
13:
14: print multipart_init;
15: foreach my $image (SJPEGS) {
16:
print multipart start(-type => 'image/jpeg');
17:
18:
open(IMAGE, "$imagedir/$image") )|
die " $image: $!";
348

III. CGI- Per!

19:
20:
21:
22:
23:
2.41 }

binmode(STDOUT); binmode(IMAGE); I Windows NT/95/98


print <IMAGE>;
close(IMAGE);
print multipartend;
sleep 5;
:

, 23.2, , 20- , "


HTML- CGI-", , 23.1.
, , 16:
multipart_start(-type => 'image/ jpeg'). , HTML Web- CGI-
JPEG. CGI-
JPEG-, HTML-, <IMG SRO.

Web- . HTML- , (
URL), . , HTML-, <HEAD> Web-,
http://foo.bar.com 6 .
< HTTP-EQUIV=Tefresh" C0NTENT="6;http://foo.bar.com">
CGI .
Web- -Refresh
header CGI ,
:
print header(-Refresh => '6;URL=http://foo.bar.com');

"". , , ( ), cookie , URL, , .. , .
,
Web- Perl- . ,
, , .
,
(
).
"" , Internet Explorer.

"" .

23- . Push- Web-

349

CGI-,
- . " "
.


Web- ,
. , Web-. . 23.3.

This Page Has Been Visited

. 23.3. Web-
. ,
? ,
"" . , ? . - Web-, , . , .
, . , . .
? , .
, , , , . ,
#1? ,
. , ,
,
. , . Web ,
Web- "", .

350

III. CGI- Perl

, , Web-, , . Web (
, Web-).
- , AltaVista, Google HotBot ? "" Web, "" ,
"" .
Refresh () Web-.
"" "". ,
, , ?
. 17- ,
" CGI", Web-.
, . 23.4.
Web- Internet (ISP), aol.com home.com , ISP , proxy-. Web-
Web-. Web-
proxy-, "" Internet . proxy-
"" (. 23.5). -
, proxy- Internet, a
( ) .

Proxy

Web-

^ .

. 23.4. Proxy- ""


Web-cepeep
Proxy

T ^
"-,

. 23,5. Proxy-
proxy- , .
remotejiost , ,
.

23- . Push- Web-

351

Web, , - (firewall),
proxy-. , ,
, proxy-.

, ,

, , ,
,
Web-. Web-:
. , , "" .
(server-side include ~ SSI),
20- , " HTML- CGI-". , ,
CGI- hits.cgi,
SSI :
<!fexec

cgi="/cgi-bin/hits.cgi">

CGI- 23.3.

23.3. Web-
1: j!/usr/bin/perl -w
2:
3: use strict;
4: use Fcntl qw(:flock);
5: use CGI qw(:all);
6:
7: my $semaphore_file='/tmp/webcount_lock';
8: my $counterfile='/web/httpd/countfile';
9: sub getlock {
10:
open(SEM, ">$semaphore_file")
11:
|j die "Be : $!";
12: flock(SEM, LOCK_EX) || die " : $!";
13: >
14: ft
15: sub release_lock {
16:
close(SEM);
17: }
18: get_lock{); f .
19: my $hits=0;
20: if ( open{CF, $counterfile) } {
21:
$hits=<CF>;
22:
close(CF);
23: }
24: $hits++; t 1.
25: print header;
26: print " $hits ";
27:
352

III. CGI- Perl

28:
29:
30:
31:
32:

openfCF, ">$counterfile") j|
die " $counterfile: $!";
print CF $hits;
close(CF);
release lockQ;

)'1. * .

18: ,
.

2023. , $counterfile. .
2830. ,
$counterfile.

32. .

, 23.3,
.
, 15- , " Perl".
, Web-.
Web- ,
,
, .
.


, . . , ,
.
Web-.
CGI- Perl,
. GD, CPAN, Perl-. ,
. , GD
.
10 , 0 9.
HTML- <IHG>, (. 23.6). ,
, , . CGI-
Perl, 23.4, ,
: digit_O.jpg, digit_l.jpg .., digit 9.jpg.

23- . Push- Web-

353

<IMG SRC="digit_l.jpg">
<IMG SRC"digit_O.jpg">
<IMG SRC="digit_3.jpg">
<IKG SRC="digit_4.jpg">

1 0 3 4

. 23.6.
CGI-
, 20- , " HTML-
CGI-". , , CGI-
graphicalJiits.cgi, SSI :
<!--} cgi="/cgi-bin/graphical_hits.cgi"-->

Web-
23.4.

23.4. Web-
1: f !/usr/bin/perl -w
2:
3: use strict;
4: use Fcntl qv(:flock);
S: use CGI gw(:all);
6:
7: my $lockfile='/tmp/webcount lock';
8: my $counterfile='/web/httpd7countfile';
9: my $image_url='http://www.server.com/images';
10:
11: sub get_lock {
12: open(SEM, ">$lockfile")

13:
|| die "He : $!";
14:
flock{SEH, LOCK EX) || die " : $!";
15: }
16: sub release_lock {
17:
close(SEM);
18: }
19: get_lock{); # .
20: my $hits=0;
21: if ( open(CF, $counterfile) ) {
22:
$hits=<CF>;
23:
close(CF);
24: }
25: $hits++;
26:
27: open(CF, ">$counterfile") ||
die " $counterfile: $!";
28: print CF $hits;
29: close(CF);
30: release_lock(); I
31:
32: jf <IMG>.
33: print header;
34: foreach my $digit (split(//, $hits)) {
35:
print "<IMG SRC=$image_url/digit_digit.jpg>";
36: }

354

III. CGI- Perl

I 23.4 23.3, .
9. $image_url URL . , URL, ,
, .
3435. $hits - , $digit.
<IMG>.


Web-.
(server push), Web-.
,

(client pull). , Web-, .

. -, push . -, Web-
CGI- . , , CGI- . CGI- ,
.
, Web-?

.
, . (. 20- , " HTML- CGI"). . POST HTML- , proxy-.


1. CGI
?
a) multipart start multipart_end.

23- . Push- Web-

355

) multipart_init, multipart_start multipart_end.


) push_start push_end.
2. ,
HTML-.
) ;
) .
3. Web- proxy- ?
) HTML-, POST;
) , ;
) CGI-.

1. ). multipart_init
Web-.
multipart_start multipart_end
.
2. ). , . , <> .
, -Refresh header ,
;
.
3. ). "
".

CGI- 23.3 (
23.4),
.
. ,
.

356

III. CGI- Perl

24-

Web-
CGI- Web- , , , .
Web ,
. Web- ,
- . , , .
-, Web-,
. , ,
. , .
, , ,
. Internet,
.
.
.
Web-.

Web- .


, , Web-,
, ,
. , Web-,
.

24- . Web-

357

: , , Web-, ""
. . . 24.1 , .
,

Web-

. 24.1. Web-,

, , V/- CGl- Web-. ,


.

:
.
. -, ,
, ( Web - ), , , . Web- .
Web-,
, , .
Internet.
Web, . Web ,
, .
, , .
,
, , .

358

III. CGI- Perl

, " " Web, .. ,


. , , .

, ""
.
, .

Web- Slashdot.Org, " ", , , Perl. ,


Web-,
. , ,
Web- FAQ http://www.slashdot.org.

: "
Slashdot.Org Web- .
1. CGI- headlines.cgi
Web-.
2. CGI- , . , .

""
Web-
Slashdot.Org.
3. CGI-
Web-.
"" Web- -
Web- LWP::Simple, Perl. LWP "" Internet : Web, FTP, ..
LWP::Simple libwww-perl.
"" Web-,
HTML- URL, Web- . ,
. libwww-perl -, .
LWP::Simple, "" Web-
:
use LWP::Simple qw(get);
$content=get("http://www.slashdot.org");
$content Web-, URL. , ?

24- . Web-

359

"" Slashdot 24.124.3. , Web-.

24.1. "" Slashdot: I


1: t!/usr/bin/perl -w
2:
3: use strict;
4: use Fcntl gy(:flock);
5: use LWP::Simple qw(get);
6: use CGI qw(:all);
7:
8J
9:
10:
11:
12:

my $url="http:/'/slashdot.org/slashdot.xml";
my $cache="/tmp/slashcache";
my $lockfile="/tmp/slashlock";
sub get_lock {
open(SEH, ">$lockfile")

13:
|| die " : $1";
14: flockjSEH, LOCK_EX) |[ die " : $!'
15: }
16: sub release_lock {
17: close(SEH);
18: }
\ .
36. . Fcntl, ,
.
LWP:: Simple, get,
"" Web- Slashdot. , ,
CGI, CGI-.
8. URL , .
:
<story>
<title>Ask Slashdot: Internet Voting?</title>
<url>http://slashdot.org/askslashdot/99/09/05/1732249.shtml</url>
<time>1999-09-05 21:34:36</time>
<author>Cliff</author>
<story>.

XML. , Perl-.
9. $cache , Slashdot.
Slashdot, , .

360

III. CGI- Perl

11-18. get_lock() 1_1()


, .
, , $cache, , , , .

24.2. "" Slashdot: II


19:
20: print header;
21: t - ,
22: get_lock();
23: if ( (not -e cache ) or < (-H $cache) > .04)} {
my $doc=get($url);
24:
if (defined $doc) {
25:
26:
open(CF, ">$cache") || die " : $1";
27:
print CF $doc;
28:
close(CF);
29:
30:
31: release lock();
32:

23. : -
60 , . - Perl Perl-. .
, , - 1; 6 , - 0.25 ( );
, - 0.0416666 ( 1/24).

24. get LWP::Simple URL, .


,
$doc, -. get
, undef, 25.

, get_lock() release_lock()
" " if. .
CGl- -, , , - .

24.3. "" Slashdot: III


33: print <H2>Slashdot.Org's Headlines as of ",
34:
scalar(gmtime((stat $cache)[9])),
35:
'GMT </B2>Updated HourlyKP>";
36:
37: open(CF, $cache) [j die " -: $!";
38: my($title, Slink);
39: while(<CP>) {
40:
if (m,<title>{.*)</title>,) {
24- . Web-

361

41:
$title=$l;
42:
}
43:
if (,<1>{.*)</1>,) {
44:
$link=$l;
45:
print qq<<A HREF="$link">$title</A><BR>\n};
46:
47:
>
48: }
49:

print " Slashdot.Org;",


" .
closefCF);
.

50:

.
3335.
-.

34. ,
. stat , $cache, .
9- ( ) . ,
, local time, .

4043. <title> <url> Slashdot.


URL $1, Stitle $link .

45. <url> <title>,


<url> $title $link
.


HTML-. , XML-
Slashdot ,
XML-. , , Slashdot, , .
, (.. )
, . 24.2.
, HTML, .

?
-. , ,
, . .
,
.
: , .

362

III. CGI- Perl

Web-
.txt. , ,
.


j$ Netccapi!
Ete

,Re
L
ahon[htp/
olo
acd

Seaidi

Netscape

Wealhel | Oe&MtNews \

AciivePaiHeip j !

Slashdot.Org's Headlines as of Sat Sep 11 19:10:36 1999


Updated Hourly!
Cloj; cut to Microsoft Ariii-Ti-;t Case
How Free is BIND 3 2?
Lmus 2 A Feahif t- Freeze
US-RusFia Joint Force to '. Missiles' YZK Problems
"White House Check; Out Open Source
Steaming Heap of Quickies
Compaq Announces Thin Ckettf RunTime LITAI:-;
CyViercoramurnsm and tbe Clift Culture
Ajiareesei't Ho Longer AOL
Aimsa di'Ofipm-f tilaiis for ntvv macbne
Copyright Slaahdot Org, used with permission

Document Done

. 24.2. slashdot.cgi
.txt, , , ,
. 24.3.
http //dial ru kiev ua/cqi-bin/dispsurv pi - M i c r o s . . . !
^

%&

O^ifflt



f
*~

'

. 24.3,

24- . Web-

363

, CGI , .
, .txt-
, CGI- . .
(Submit), CGI-,
, , . foo.txt, foo.answer. CGI- , .

I:
. , ,
,txt. ,
, , , .

24.4. , I
1: #!/usr/bin/perl -w
2:
3: use strict;
4: use CGI qw(:all);
5: my($survey_dir);
6: $survey_dir="/web/htdocs/poll";
7:
8: sub find_last_file {
9:
my($type)=e_;
10:
my(gfiles, $last_file);
11:
It
12:
i .
13:
opendir{SD, $survey_dir) ||
die " $survey_dir: $1";
14:
efiles=reverse sort grep(/\.$type$/, readdir SD);
15:
closedir(SD);
16:
$last_file=$files[$#filesl;
17:
return($last_file);
18: }
19:
20: sub get_file_contents {
21:
my($type)=_;
22:
my(answers, $last file);
23:
24:
$last_file=find_last_file($type);
25:
26:
' return if (not defined $last file);
27:
I .
28:
open(QF, "$survey_dir/$last_file")
364

III. CGI- Perl

29:
30:
31:
32:
33:
34: )

|| die " $last_file: $I";


8answers=<QF>;
close(QF);
chomp ("answers; t
return(^answers);
-

'} \~ ? .

6. $survey_dir , . , .txt , . Web-. 0755 UNIX


guest Windows NT.

8. find_last file{) ( .txt, .answer).


$survey_dir . get_file_contents(),
,
. ,
find_last_file(} .undef.

20. get_file_contents(} (- .txt .answer). . , find_last_file().

, 24.5, .

24.5. , I)
35:
36:
37: my($question, Sanswers)=get_file_contents("txt");
38:
39: print header;
40: print qq{<FORM ACTIOR="/cgi/writesurvey.cgi" HETHOD=POST>\n};
41: print ": $question<P>\n";
42: my $answer=0;
43: foreach{answers) {
44:
p r i n t -<INPtfT TYPE=RADIO NAME=answer value=$answer>";
45:
p r i n t "$_<BR>\n";
46:
$answer++;
47: )
48: print qq{<INPUT TYPE=SUBMIT VALUE="3anpoc">};
49: print qq{</FORM>};
_^^___^__^_____^_^^
36. .txt $question ^answers get file contents!).

24- . Web-

365

40 /cgi/writesurvey.cgi CGI- .
.
^answers .
0, 1 .. ,
^answers . :
<INPUT TYPE=RADIO NAME=answer value=0>Co6aKa<BR>
<INPUT TYPE=RADIO NAME=answer value=l>KoiDKa<BR>
<INPUT TYPE=RADIO NAME=answer value=2>Pu6KH<BR>

<INPUT TYPE=RADIO NAME=answer value=3> <>



, CGI- answer, .
CGI- /cgi/writesurvey.cgi, (
40), .
.

II:
(Submit), . (.. )
, , .
, , ,
, . get_lock{) release_lock{), , get_file_contents()
find_last_file()
CGI-.
24.6.
: ,
.

24.6. , I
1: fl/usr/bin/perl -w
2:
3: use. strict;
4: use Fcntl qv(:flock);
5: use CGI gw(:all);
6:
7: my($survey_dir, $lockfile);
8: $survey_dir="/web/htdocs/poll";
9: jlockfile="/tmp/surveylock";
10:
11: sub find last_file {
12:
my($type)=g_;
13:
my{files, $last_file);
14:
I ,
15:
* .
16:
opendir(SD, $survey_dir) |[
die " $survey dir: $1";
17:
files=reverse sort grep(/\.$type$/, readdir SD);
18:
closedir(SD);
366

III. CGI- Perl

19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:

42:
43:
44:
45:

$last_file=$files[$*files];
return{$last_file);
sub get_file_contents {
my(janswers7 $last_file);
$last_file=find_last_file($type);
return if (not defined $last_file);
#
open(QF, "$surveyjiir/$last_file")
|| die " $last_file: $!";
(!answers=<QF>;
close(QF);
chomp ^answers; i
return{ I! answers);
sub get_lock {
open SEM, ">$lockfile")
| die " : $1";
flock(SEM, LOCK_EX)
|| die " : $1";
sub release_lock {
close(SEH);
}

..

...

._

24.6 .

,
,
,
get_file_contents() find_last_file(), get_lock()
release_lock(). - , Web-
, $survey_dir).
, , 24.7.

24.7. , II
46: my{$question, eposs_answers)=get_Jile_contents{"txt");
47:
48: print header;
49:
50:
51: if (defined param("answer")) {
52:
my($lastfile);
53:
get_lock();
54:
t
55:
t .
56:
$lastfile=find_last_file("txt");
57:
$lastfile="s/txt/answer/;
58:
59:
open(ANS, "$survey_dir/$lastfile")
60:
|| die " $lastfile: $!";
24- . Web-

367

61:
print ANS param("answer"), "\n";
62:
close(ANS);
63:
release_lock{);
64: }
65:
66: my{^answers)=getj! ile_contents("answer");
67: my(%results);
68: i
70: foreach(answers) {
71:
$results{$_}++;
72: }
73: my $ansno=0;
74: foreach my $ans (poss_answers) {
75:
$results{$ansno}=0 if (! exists $results{$ansno});
76:
print " '$ans' $results{$ansno} pa3<BR>";
77:
$ansno++;
78: }
:
46. $question @poss_answers.
50 , . ,
. , 53
get_lock(), ( !).
56 .txt- , first.txt.
.txt .answer, ..
first.answer. , , release_lock{ )c . .
66 get_file_contents()
. %results; 0,
1, 2 .., .
74 . %results , ,
0. 76.
. . 24.4 . , , CGI-
( ) , HTML- .
, CGI- , ,
( /web/htdocs/poll),
. Windows NT
, guest. UNIX chmod
, 0777. ,
,
.answer, Web-.

, , .

368

III. CGI- Peri

'' 1
' ' 3
'' 1
' ' 1

. 24.4.

, Web .
Web. , , . , ,
, Web- .


Web- , ?
, . ,
. , , , . , .txt- .answer-.
chmod .answer- .
, ,
?
. , . . 1999 Microsoft Ticketmaster, . Microsoft " " Ticketmaster, Ticketmaster . , " " .
.

24- . Web-

369

, ; -
Slashdot. XML-, .
HTML-. ?
HTML-,
, . HTML
, , . HTML-, . CPAN
HTML. HTML, .. HTML::*.


1. HTML- Web-?
) LWP;
) "" ;
) 'lynx -dump' 'netscape -print'.
2. get LWP::Simple ,
?
) "No Document";
) (.. "");
) undef.

1. ). ) ) ,
.
2. ). . , 24.2.

, . .gif- 1x1
. ,
.gif- :
<IMG SRC="small.gif" HEIGHT=20 WIDTH=2OO =""
.gif- .
: ,
. ,

370

III. CGI- Perl

, . , 100
40 ,
0,4, .

, 24.4, ,
. , ?
, ,
.
,
proxy- ( 23- , "Push- Web-")- ,
, , .
( , .
, , .)

24- . Web-

371

Perl
Perl ,
Perl. , .
,
, Perl. , perlmodinstall,
, OS/2 VMS.


.
CPAN,
http://www.perl.com/CPAN. , .
CPAN . ,
Image::Size , ;
Web-.
. , LWP Perl, libwww-perl.
CPAN. ,
. , libnet ,
. , LWP
libnet.
( .

372

-- , ,
Date::Manip CPAN. ,
Date::Manip.

...Windows 95/98/NT
Windows
, ActiveState Tool Corp, , ,
Perl .
Windows,
Perl Package Manager (PPM). ,
. ,
MS-DOS; Internet.
, . ; ,
ppm.bat, ActiveState Perl ,
.
C:\Windows>ppm

interactive shell (1.1.3) - type 'help' for available commands.


PPM>
, search,
. , ActiveState
CPAN; . , , , .
> search Date
Packages available from http://www.ActiveState.com/packages
Date-Calc
Date-Manip
TimeDate
PPH>
Date: :Manip,
install :
> install Date-Manip
Install package 'Date-Manip'?(y/N):
Installing C:\Perl\html\lib\Date\Manip.html
Installing C:\Perl\htmlhelp\pkg-Date-Hanip.html
Installing C:\Perl\htmlhelp\pkg-Date-Manip.hhc
Installing C:\Perl\site\lib\Date\Manip.pm
Writing C:\Perl\site\lib/auto/Date-Manip/.packlist
PPM>
Date: :Manip !
(,
Internet ), , , -

Perl

373

, Web- ActiveState http://vww.ActiveState.com.


ActiveState , Perl, .
, Microsoft Windows, . Pert
, ,
Perl Windows, . ,
, .

...UNIX, CPAN
UNIX ,
. ANSI
( , Perl)
( -). GNU gzip/gunzip; , UNIX, . , http://www.fsf.org.
, UNIX ( , Hewlett-Packard),
,
ANSI-. ,
GNU .
: root ,
Perl. Perl .
.
Perl CPAN, . , Perl
CPAN :
$ perl -MCPAN -e shell
, CPAN , "" Perl . , . ,
, CPAN ( ) Internet proxy-.
CPAN , :
cpan shell CPAN exploration and modules installation (vl.52)
ReadLine support available (try ' " i n s t a l l Bundle::CPAN''}
cpan>
i I'/,
. // . , Date: :Manip, :
cpan> i /Manip/

374

CPAN CPAN
. ,
. CPAN :
Distribution
Nodule

S/SB/SBECK/DateManip-5.39.tar.gz
Date::Manip
(S/SB/SBECK/DateHanip-5.39.tar.gz)

,
cpan> install Date::Manip
CPAN , , . ,
,
( # , ).
Running make for S/SB/SBECK/DateHanip-5.39.tar.gz

Fetching with Net::FTP: #


ftp://ftp.cpan.Org/CPAN/authors/id/S/SB/SBECK/DateManip-5.39.tar.gz
Fetching with Net::FTP: I
ftp://ftp.cpan.Org/CPAN/authors/id/S/SB/SBECK/CHECKSDHS
Checksum for /root/.cpan/sources/authors/id/S/SB/SBECK/DateManip-5.39.tar.gz ok
DateManip-5.39/
DateManip-5.39/t/
DateHanip-5.39/t/date_date_0.t
DateHanip-5.39/t/Hanip.cnf
DateManip-5.39/t/date.t
CPAN.pm: Going to build S/SB/SBECK/DateHanip-5.39.tar.gz
Checking if your kit is complete...
Looks good
Writing Makefile for Date::Manip
mkdir blib
*
mkdir blib/lib
mkdir blib/lib/Date
cp Manip.pod blib/lib/Date/Manip.pod
cp Hanip.pm blib/lib/Date/Manip.pm
mkdir blib/arch
mkdir blib/arch/auto
mkdir blib/arch/auto/Date
mkdir blib/arch/auto/Date/Manip
mkdir blib/lib/auto/Date
mkdir blib/lib/auto/Date/Manip
mkdir blib/man3
Manifying blib/man3/Date::Hanip-3
/usr/bin/make OK
Running make test #
PERL_DL_NONLAZY=1 /usr/bin/perl -Iblib/arch -Iblib/lib -I/usr/local/lib/perl5/5.
6.0/i386-freebsd -I/usr/local/lib/perl5/5.6.0 -e 'use Test::Harness qw(&runtests
$verbose); $verbose=0; runtests f!ARGV;' t/*.t
t/date
ok
t/date_date_O
ok
Files=31, Tests=839, 153 wallclock sees (139.67 cusr + 5.69 csys = 145.36 CPU)

Perl

375

/usr/bin/make test OK
Running make install i
Installing /usr/local/lib/perl5/site_perl/5.6.0/Date/Hanip.pod
Installing /usr/local/lib/perl5/site_perl/5.6.O/Date/Manip.pm
Installing /usr/local/man/man3/Date::Hanip.3
Writing /usr/local/lib/perl5/site_perl/5.6-.0/i386-freebsd/aiito/Date/Kanip/.packl
ist
Appending installation info to /usr/local/lib/perl5/5.6.Q/i386-freebsd/perllocal
.pod
/usr/bin/make install ~ OK
, , . , . ""!

...UNIX,
UNIX , CPAN,
.
.
CPAN , .
CPAN. tar, gzip. ,
Date: :Calc, , : Date-Calc-X.T.tar.gz. , , , :
$ gunzip Date-Calc-4.3.tar.gz
$ tar xf Date-Calc-4.3.tar.gz
Date-Calc-4.3.
cd :
$ perl Makefile.PL
Checking if your kit is complete...
Looks good
Writing Makefile for Date::Calc
makefile, . , make :
$ make
mkdir blib
mkdir blib/lib
Hanifying blib/man3/Date::Calc.3
/usr/bin/make OK
.
, ,
. make test :
$ make test
PERL_DLJJONLAZY=1 /usr/bin/perl -Iblib/arch -Iblib/lib -I/usr/local/lib/perl5/5.
6.0/i386-freebsd -I/usr/local/lib/perl5/5.6.0 -e 'use Test::Harness qw(Sruntests

376

$verbose); $verbose=0; runtests &ARGV;' t / * . t


t/fOOO
ok
t/fOOl
ok
t/fO33
ok
All t e s t s successful.
Files=34, Tests=1836, 11 wallclock sees ( 7.65 cusr +
/usr/bin/make t e s t ~ OK

1.10 csys =

8.75 CPU)

, , make test. ( )
. , .
root, .
$ su
Password: *******
i make install
Installing /usr/local/lib/perl5/site_perl/5.6.0/i386-freebsd/auto/Date/Calc/Calc
.so
Appending installation info to /usr/local/lib/perl5/5.6.0/i386-freebsd/perllocal
.pod
/usr/bin/make install OK
!


Macintosh
Macintosh . FAQ- MacPerl, (droplet), . FAQ- MacPerl http://www.macperl.com.

,

, . , . , , .
, , , .
Perl
.
-, , . ,
.

Perl

377

Microsoft Windows, , , , .
set :
> set root c:\myperl
> set build c:\myperl
c:\myperl.
UNIX, CPAN, makepl_arg :
H

> conf makepl_arg PREFIX= /horae/clintp/perl/lib"


, make,
, PREFIX .
$ perl Makefile.PL PREFIX="/home/clintp/perl/lib"
, , , /home/clintp/perl/lib/. , ,
.
,
. ,
Perl, . ,
Perl;
, . .

,

, , ,
use lib. ,
Date::Manip /home/clintp/perl/lib/
, , , .
/home
I/clintp
'/perl
I/lib
I/Date
Imanip.pm
, :
use l i b '/home/clintp/perl/lib'; i
else
use Date::Manip;
Perl, ,
.
, ,
.

378

Brooks, Frederic P., 103

CGI, 282; 285


, 325
,
325
, 284
, 289
, 288
, 287
Cookie, 336; 337
, 345

, 343
, 341
, 344
,
339
, 346
, 340
, 337
, 342
CPAN, 270

D
Droplet, 395

HTML, 282

#, 329
<FORM>, 297; 300
<INPUT>, 297
<TEXTAREA>, 297
Submit, 298
, 310
HTTP, 283
HTTPS, 302

I
IETF, 320
IIS, 286
IMAP, 351
Internet Engineering Task
Force, 320
Intranet, 282
IP-, 283

M
MacPerl, 193
Magic cookies, 337
Mail Transport Agent, 557
Microsoft Internet
Information Server, 286
MIME
, 323
, 323
MTA, 351

POP, 351
Proxy-, 369
Push-, 363

Telnet, 322

UNC, 102
Uniform Resource Locator,
283
Universal Naming
Convention, 102
URL, 283
User agent, 321
UUCP, 350
/

w
Web-, 283
Web-, 283
Web-
, 322
World Wide Web, 283

XML, 378

R
References, 218
Request For Comments, 320
RFC, 320

sendmail, 351
Server-side includes, 328
SMTP, 351
SSI, 328
,
329

, 351
, 119
, 366
, 120
, 59

, 136; 248
, 254
, 256
, 256
Web, 301
, 67

379

, 259
UNIX, 260
Windows NT, 260
, 261
, 260
, 260

, 261
,
263
, 370
, ., 103


, 328

, 185
, 56"

Web, 377

, 304

, 60

HTML, 282
STDIN, 100
, 173
, 173
, 100
, 84

use strict, 15a, 166; 177


, ,
365
, 395

, 375

undef, 72

380

, 300
, 323
, 57; 59
, 38
, 71
, 92

, 172; 178
, 173
, 173
, 178
, 179
, 178
, 180
, 173
, 116
, 52
, 117

ASCII, 71

chmod, 182
pwd, 178
Perl, 191
, 47
, 195
,
195
, 90
, 51
, 87; 88

, 57; 52
, 52
, 52

_FILE__, 274
_ L I N E _ , 274
, 155

, /55
, 185

, 91
, 83; 85
@_, 223
@ARGV, 215
, 224
, 83; 128
, 225
, 86
, 86
, 87

, 92
, 169
, 87
, 93; 169

, 94
, 114; 115
, 120
, 116
, 117
, 116
, 116
, 115
, 78


, 367

, 367
, 179; 234
CGI, 300
PAN, 392
Cwd, 179
Data::Dumper, 140; 228;
265
diagnostics, 242
English, 242
File::Copy, 241
FiIe::Find, 238
GD, 371
HTML::*, 388
1::2, 202
LWP::Simple, 377
Net::Ping, 241
Net::SMTP, 352; 355
Tie::IxHash, 140
, 390
, 238
,
236
, 243


, 142;
146
, 152
, 152
, 124
, 357
, 54

, 60

... 84
<=>, 94
<STDIN>, 60
=~, 122
chomp, 61
cmp, 94
else, 68
exit, 78
for, 75
foreach, 92
glob, 175
if, 67

int. 69

last, 77; 139


local, 151
my, 147; 148
next, 77
q, 54
qq, 54
qw, #4
qx1', /95
qx{}, 194
require, 246
return, 143; 144
sort, 166
tr///, 162
use, Z?5
use Cwd, 179
use strict, /52
while, 75

y//A /

, #4
, 90
-, /29
, 57
, 72
, 56
, 69
, 70
, 58; 90

, 120
, 120; 193
, 123
, 123
, 122
, 67
, 67
, 57
, 104
, 59
, 77
, 66
, 104
, 57
,
199

,
227
, 205
, 211

[h, 207
b, 209
c, 209
d, 209
h, 207
1, 208; 209
,207
q, 211
, 209
s, 210
, 228
, 207
,
209
,
207

, 209
,
208
, 208
, 209
, 209
, 209
,
210
,
365
, 164

gzip, 42
libnet, 356
libwww-perl, 377
MacPerl, 43

, 224
, 172
, 332
, 161

$!, 104
$#_, 87
$_, 55; 93; 105
SARG, 242
@_, 145
, 147
, 55
, 151
, 147
, 147
, 51; 54

, 179
, 332
,
197
, 198
, 162
, 142
,
222
, 223
, 223
, /55
, 120
Web-,
327
,
321
2000, 91

, 103
-,
198

chmod, 49
EDIT.EXE, 45
gunzip, 42
man, 44
perl doc, 43

381

sendmail, 351
Shuck, 44
Stufflt Expander, 43
, 212

HTTP, 320
, 322
,
320
, 102

, 220
,
93;
, 775
, 755

, 208
, 161

, 218

, 283
Perl, 39
Macintosh, 43
UNIX, 41
Windows, 41

grep, 176
perldoc, 59
PPM, 245
telnet, 322

, 375
, 352

, 282

$,54
@, 83; 87
, 720
, 120
, 57
, 158

,
102
, 83, 131
, 352
, 219
, 222
, 221
, 221
, 218
, 167
, 52; 105
, 227
,
368
, 371
, 370

382

, 772
, 172
cookie, 336
, 345

, 343
, 341
, 344

, 339
, 346
, 340
, 337
, 342
cookies.txt, 343
DBM, 140; 248
stable.tar.gz, 42
, 109
, 112
, 100
STDERR, 109
STDIN, 109
STDOUT, 109
, 107
, 90; 105
, 240
, 108
, 174
, 100
, 181

, 181
,
258
, 238
,
183
, 182

., 236

, 257
, 257
, 262
, 110
, 180
, 258
, 104
, 755

ActiveState Tool, 41
, 296
GET,
300
POST,
300
, 299
, 142
binmode, 109; 324
chdir, 179
chmod, 183
chomp, 89; 105
close, 102; 107
closedir, 173
cookie, 337; 341
copy, 241
cwd, 179, 235; 236
dbmclose, 249
dbmopen, 249
delete, 133
die, 101; 104
each, 251
escape, 327
exists, 133
fastgetcwd, 236
find, 238
flock, 260
get, 378
getc, 772
getcwd, 236
glob
, 176
grep, 124; 257
header, 323

index, 159
keys, 130
length, 160
localtime, 90; 330
map, 125
mkdir, 179; 183
move, 241
multipart_end, 366
multipart_init, 366
multipart_start, 366
open, 101
opendir, 173
param, 299; 326
pingecho, 242
pop, 167
print, 107; 109; 162
printf, 163
push, 140; 167; 256
rand, 69
readdir, 173
redirect, 333; 348
referer, 331
remote_host, 331; 360
remote_user, 360
reverse, 95; 131
rindex, 160
rmdir, 180
scalar, 89
script_name, 331; 345
seek, 258
send_mail, 354; 355; 357
server_name, 331
sort, 94; 136
splice, 169; 256
split, 92

sprintf, 164
stat, 183
substr, 161
system(), 191

, 192

,
193
tell. 258
unlink, 180
unshift, 256
user_agent, 331
values, 131
virtual_host, 331
warn, 104


, 331
, 146
rand, 96

, 83; 128
, 224
, 130
, 131
, 132
, 129
, 136
, 133

, 74
for, 75
foreach, 92
while, 75; 105

, 52
, 79
, 156

, 114
, 119
, 119


, 350
, 351
UNIX, 354
Web-, 357
UNIX, 355
sendmail, 354
SMTP, 355
, 310


, 38; 190

383

Perl
24

"".
101509, , . , . 43, . 1.
. . 090230 23.06.99
.

12.02.01. 70x100/16.
Times. . .
.-. . 21,86. . . . 26,23. . 4000 . 15.
,
.
197110, -, ., 15.