1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
|
''' Beginning of part 2
''' $Header: perl_man.2,v 3.0.1.9 90/10/15 18:17:37 lwall Locked $
'''
''' $Log: perl.man.2,v $
''' Revision 3.0.1.9 90/10/15 18:17:37 lwall
''' patch29: added caller
''' patch29: index and substr now have optional 3rd args
''' patch29: added SysV IPC
'''
''' Revision 3.0.1.8 90/08/13 22:21:00 lwall
''' patch28: documented that you can't interpolate $) or $| in pattern
'''
''' Revision 3.0.1.7 90/08/09 04:27:04 lwall
''' patch19: added require operator
'''
''' Revision 3.0.1.6 90/08/03 11:15:29 lwall
''' patch19: Intermediate diffs for Randal
'''
''' Revision 3.0.1.5 90/03/27 16:15:17 lwall
''' patch16: MSDOS support
'''
''' Revision 3.0.1.4 90/03/12 16:46:02 lwall
''' patch13: documented behavior of @array = /noparens/
'''
''' Revision 3.0.1.3 90/02/28 17:55:58 lwall
''' patch9: grep now returns number of items matched in scalar context
''' patch9: documented in-place modification capabilites of grep
'''
''' Revision 3.0.1.2 89/11/17 15:30:16 lwall
''' patch5: fixed some manual typos and indent problems
'''
''' Revision 3.0.1.1 89/11/11 04:43:10 lwall
''' patch2: made some line breaks depend on troff vs. nroff
''' patch2: example of unshift had args backwards
'''
''' Revision 3.0 89/10/18 15:21:37 lwall
''' 3.0 baseline
'''
'''
.PP
Along with the literals and variables mentioned earlier,
the operations in the following section can serve as terms in an expression.
Some of these operations take a LIST as an argument.
Such a list can consist of any combination of scalar arguments or array values;
the array values will be included in the list as if each individual element were
interpolated at that point in the list, forming a longer single-dimensional
array value.
Elements of the LIST should be separated by commas.
If an operation is listed both with and without parentheses around its
arguments, it means you can either use it as a unary operator or
as a function call.
To use it as a function call, the next token on the same line must
be a left parenthesis.
(There may be intervening white space.)
Such a function then has highest precedence, as you would expect from
a function.
If any token other than a left parenthesis follows, then it is a
unary operator, with a precedence depending only on whether it is a LIST
operator or not.
LIST operators have lowest precedence.
All other unary operators have a precedence greater than relational operators
but less than arithmetic operators.
See the section on Precedence.
.Ip "/PATTERN/" 8 4
See m/PATTERN/.
.Ip "?PATTERN?" 8 4
This is just like the /pattern/ search, except that it matches only once between
calls to the
.I reset
operator.
This is a useful optimization when you only want to see the first occurrence of
something in each file of a set of files, for instance.
Only ?? patterns local to the current package are reset.
.Ip "accept(NEWSOCKET,GENERICSOCKET)" 8 2
Does the same thing that the accept system call does.
Returns true if it succeeded, false otherwise.
See example in section on Interprocess Communication.
.Ip "atan2(X,Y)" 8 2
Returns the arctangent of X/Y in the range
.if t \-\(*p to \(*p.
.if n \-PI to PI.
.Ip "bind(SOCKET,NAME)" 8 2
Does the same thing that the bind system call does.
Returns true if it succeeded, false otherwise.
NAME should be a packed address of the proper type for the socket.
See example in section on Interprocess Communication.
.Ip "binmode(FILEHANDLE)" 8 4
.Ip "binmode FILEHANDLE" 8 4
Arranges for the file to be read in \*(L"binary\*(R" mode in operating systems
that distinguish between binary and text files.
Files that are not read in binary mode have CR LF sequences translated
to LF on input and LF translated to CR LF on output.
Binmode has no effect under Unix.
If FILEHANDLE is an expression, the value is taken as the name of
the filehandle.
.Ip "caller(EXPR)"
.Ip "caller"
Returns the context of the current subroutine call:
.nf
($package,$filename,$line) = caller;
.fi
With EXPR, returns some extra information that the debugger uses to print
a stack trace. The value of EXPR indicates how many call frames to go
back before the current one.
.Ip "chdir(EXPR)" 8 2
.Ip "chdir EXPR" 8 2
Changes the working directory to EXPR, if possible.
If EXPR is omitted, changes to home directory.
Returns 1 upon success, 0 otherwise.
See example under
.IR die .
.Ip "chmod(LIST)" 8 2
.Ip "chmod LIST" 8 2
Changes the permissions of a list of files.
The first element of the list must be the numerical mode.
Returns the number of files successfully changed.
.nf
.ne 2
$cnt = chmod 0755, \'foo\', \'bar\';
chmod 0755, @executables;
.fi
.Ip "chop(LIST)" 8 7
.Ip "chop(VARIABLE)" 8
.Ip "chop VARIABLE" 8
.Ip "chop" 8
Chops off the last character of a string and returns the character chopped.
It's used primarily to remove the newline from the end of an input record,
but is much more efficient than s/\en// because it neither scans nor copies
the string.
If VARIABLE is omitted, chops $_.
Example:
.nf
.ne 5
while (<>) {
chop; # avoid \en on last field
@array = split(/:/);
.\|.\|.
}
.fi
You can actually chop anything that's an lvalue, including an assignment:
.nf
chop($cwd = \`pwd\`);
chop($answer = <STDIN>);
.fi
If you chop a list, each element is chopped.
Only the value of the last chop is returned.
.Ip "chown(LIST)" 8 2
.Ip "chown LIST" 8 2
Changes the owner (and group) of a list of files.
The first two elements of the list must be the NUMERICAL uid and gid,
in that order.
Returns the number of files successfully changed.
.nf
.ne 2
$cnt = chown $uid, $gid, \'foo\', \'bar\';
chown $uid, $gid, @filenames;
.fi
.ne 23
Here's an example of looking up non-numeric uids:
.nf
print "User: ";
$user = <STDIN>;
chop($user);
print "Files: "
$pattern = <STDIN>;
chop($pattern);
.ie t \{\
open(pass, \'/etc/passwd\') || die "Can't open passwd: $!\en";
'br\}
.el \{\
open(pass, \'/etc/passwd\')
|| die "Can't open passwd: $!\en";
'br\}
while (<pass>) {
($login,$pass,$uid,$gid) = split(/:/);
$uid{$login} = $uid;
$gid{$login} = $gid;
}
@ary = <${pattern}>; # get filenames
if ($uid{$user} eq \'\') {
die "$user not in passwd file";
}
else {
chown $uid{$user}, $gid{$user}, @ary;
}
.fi
.Ip "chroot(FILENAME)" 8 5
.Ip "chroot FILENAME" 8
Does the same as the system call of that name.
If you don't know what it does, don't worry about it.
If FILENAME is omitted, does chroot to $_.
.Ip "close(FILEHANDLE)" 8 5
.Ip "close FILEHANDLE" 8
Closes the file or pipe associated with the file handle.
You don't have to close FILEHANDLE if you are immediately going to
do another open on it, since open will close it for you.
(See
.IR open .)
However, an explicit close on an input file resets the line counter ($.), while
the implicit close done by
.I open
does not.
Also, closing a pipe will wait for the process executing on the pipe to complete,
in case you want to look at the output of the pipe afterwards.
Closing a pipe explicitly also puts the status value of the command into $?.
Example:
.nf
.ne 4
open(OUTPUT, \'|sort >foo\'); # pipe to sort
.\|.\|. # print stuff to output
close OUTPUT; # wait for sort to finish
open(INPUT, \'foo\'); # get sort's results
.fi
FILEHANDLE may be an expression whose value gives the real filehandle name.
.Ip "closedir(DIRHANDLE)" 8 5
.Ip "closedir DIRHANDLE" 8
Closes a directory opened by opendir().
.Ip "connect(SOCKET,NAME)" 8 2
Does the same thing that the connect system call does.
Returns true if it succeeded, false otherwise.
NAME should be a package address of the proper type for the socket.
See example in section on Interprocess Communication.
.Ip "cos(EXPR)" 8 6
.Ip "cos EXPR" 8 6
Returns the cosine of EXPR (expressed in radians).
If EXPR is omitted takes cosine of $_.
.Ip "crypt(PLAINTEXT,SALT)" 8 6
Encrypts a string exactly like the crypt() function in the C library.
Useful for checking the password file for lousy passwords.
Only the guys wearing white hats should do this.
.Ip "dbmclose(ASSOC_ARRAY)" 8 6
.Ip "dbmclose ASSOC_ARRAY" 8
Breaks the binding between a dbm file and an associative array.
The values remaining in the associative array are meaningless unless
you happen to want to know what was in the cache for the dbm file.
This function is only useful if you have ndbm.
.Ip "dbmopen(ASSOC,DBNAME,MODE)" 8 6
This binds a dbm or ndbm file to an associative array.
ASSOC is the name of the associative array.
(Unlike normal open, the first argument is NOT a filehandle, even though
it looks like one).
DBNAME is the name of the database (without the .dir or .pag extension).
If the database does not exist, it is created with protection specified
by MODE (as modified by the umask).
If your system only supports the older dbm functions, you may only have one
dbmopen in your program.
If your system has neither dbm nor ndbm, calling dbmopen produces a fatal
error.
.Sp
Values assigned to the associative array prior to the dbmopen are lost.
A certain number of values from the dbm file are cached in memory.
By default this number is 64, but you can increase it by preallocating
that number of garbage entries in the associative array before the dbmopen.
You can flush the cache if necessary with the reset command.
.Sp
If you don't have write access to the dbm file, you can only read
associative array variables, not set them.
If you want to test whether you can write, either use file tests or
try setting a dummy array entry inside an eval, which will trap the error.
.Sp
Note that functions such as keys() and values() may return huge array values
when used on large dbm files.
You may prefer to use the each() function to iterate over large dbm files.
Example:
.nf
.ne 6
# print out history file offsets
dbmopen(HIST,'/usr/lib/news/history',0666);
while (($key,$val) = each %HIST) {
print $key, ' = ', unpack('L',$val), "\en";
}
dbmclose(HIST);
.fi
.Ip "defined(EXPR)" 8 6
.Ip "defined EXPR" 8
Returns a boolean value saying whether the lvalue EXPR has a real value
or not.
Many operations return the undefined value under exceptional conditions,
such as end of file, uninitialized variable, system error and such.
This function allows you to distinguish between an undefined null string
and a defined null string with operations that might return a real null
string, in particular referencing elements of an array.
You may also check to see if arrays or subroutines exist.
Use on predefined variables is not guaranteed to produce intuitive results.
Examples:
.nf
.ne 7
print if defined $switch{'D'};
print "$val\en" while defined($val = pop(@ary));
die "Can't readlink $sym: $!"
unless defined($value = readlink $sym);
eval '@foo = ()' if defined(@foo);
die "No XYZ package defined" unless defined %_XYZ;
sub foo { defined &bar ? &bar(@_) : die "No bar"; }
.fi
See also undef.
.Ip "delete $ASSOC{KEY}" 8 6
Deletes the specified value from the specified associative array.
Returns the deleted value, or the undefined value if nothing was deleted.
Deleting from $ENV{} modifies the environment.
Deleting from an array bound to a dbm file deletes the entry from the dbm
file.
.Sp
The following deletes all the values of an associative array:
.nf
.ne 3
foreach $key (keys %ARRAY) {
delete $ARRAY{$key};
}
.fi
(But it would be faster to use the
.I reset
command.
Saying undef %ARRAY is faster yet.)
.Ip "die(LIST)" 8
.Ip "die LIST" 8
Prints the value of LIST to
.I STDERR
and exits with the current value of $!
(errno).
If $! is 0, exits with the value of ($? >> 8) (\`command\` status).
If ($? >> 8) is 0, exits with 255.
Equivalent examples:
.nf
.ne 3
.ie t \{\
die "Can't cd to spool: $!\en" unless chdir \'/usr/spool/news\';
'br\}
.el \{\
die "Can't cd to spool: $!\en"
unless chdir \'/usr/spool/news\';
'br\}
chdir \'/usr/spool/news\' || die "Can't cd to spool: $!\en"
.fi
.Sp
If the value of EXPR does not end in a newline, the current script line
number and input line number (if any) are also printed, and a newline is
supplied.
Hint: sometimes appending \*(L", stopped\*(R" to your message will cause it to make
better sense when the string \*(L"at foo line 123\*(R" is appended.
Suppose you are running script \*(L"canasta\*(R".
.nf
.ne 7
die "/etc/games is no good";
die "/etc/games is no good, stopped";
produce, respectively
/etc/games is no good at canasta line 123.
/etc/games is no good, stopped at canasta line 123.
.fi
See also
.IR exit .
.Ip "do BLOCK" 8 4
Returns the value of the last command in the sequence of commands indicated
by BLOCK.
When modified by a loop modifier, executes the BLOCK once before testing the
loop condition.
(On other statements the loop modifiers test the conditional first.)
.Ip "do SUBROUTINE (LIST)" 8 3
Executes a SUBROUTINE declared by a
.I sub
declaration, and returns the value
of the last expression evaluated in SUBROUTINE.
If there is no subroutine by that name, produces a fatal error.
(You may use the \*(L"defined\*(R" operator to determine if a subroutine
exists.)
If you pass arrays as part of LIST you may wish to pass the length
of the array in front of each array.
(See the section on subroutines later on.)
SUBROUTINE may be a scalar variable, in which case the variable contains
the name of the subroutine to execute.
The parentheses are required to avoid confusion with the \*(L"do EXPR\*(R"
form.
.Sp
As an alternate form, you may call a subroutine by prefixing the name with
an ampersand: &foo(@args).
If you aren't passing any arguments, you don't have to use parentheses.
If you omit the parentheses, no @_ array is passed to the subroutine.
The & form is also used to specify subroutines to the defined and undef
operators.
.Ip "do EXPR" 8 3
Uses the value of EXPR as a filename and executes the contents of the file
as a
.I perl
script.
Its primary use is to include subroutines from a
.I perl
subroutine library.
.nf
do \'stat.pl\';
is just like
eval \`cat stat.pl\`;
.fi
except that it's more efficient, more concise, keeps track of the current
filename for error messages, and searches all the
.B \-I
libraries if the file
isn't in the current directory (see also the @INC array in Predefined Names).
It's the same, however, in that it does reparse the file every time you
call it, so if you are going to use the file inside a loop you might prefer
to use \-P and #include, at the expense of a little more startup time.
(The main problem with #include is that cpp doesn't grok # comments\*(--a
workaround is to use \*(L";#\*(R" for standalone comments.)
Note that the following are NOT equivalent:
.nf
.ne 2
do $foo; # eval a file
do $foo(); # call a subroutine
.fi
Note that inclusion of library routines is better done with
the \*(L"require\*(R" operator.
.Ip "dump LABEL" 8 6
This causes an immediate core dump.
Primarily this is so that you can use the undump program to turn your
core dump into an executable binary after having initialized all your
variables at the beginning of the program.
When the new binary is executed it will begin by executing a "goto LABEL"
(with all the restrictions that goto suffers).
Think of it as a goto with an intervening core dump and reincarnation.
If LABEL is omitted, restarts the program from the top.
WARNING: any files opened at the time of the dump will NOT be open any more
when the program is reincarnated, with possible resulting confusion on the part
of perl.
See also \-u.
.Sp
Example:
.nf
.ne 16
#!/usr/bin/perl
require 'getopt.pl';
require 'stat.pl';
%days = (
'Sun',1,
'Mon',2,
'Tue',3,
'Wed',4,
'Thu',5,
'Fri',6,
'Sat',7);
dump QUICKSTART if $ARGV[0] eq '-d';
QUICKSTART:
do Getopt('f');
.fi
.Ip "each(ASSOC_ARRAY)" 8 6
.Ip "each ASSOC_ARRAY" 8
Returns a 2 element array consisting of the key and value for the next
value of an associative array, so that you can iterate over it.
Entries are returned in an apparently random order.
When the array is entirely read, a null array is returned (which when
assigned produces a FALSE (0) value).
The next call to each() after that will start iterating again.
The iterator can be reset only by reading all the elements from the array.
You must not modify the array while iterating over it.
There is a single iterator for each associative array, shared by all
each(), keys() and values() function calls in the program.
The following prints out your environment like the printenv program, only
in a different order:
.nf
.ne 3
while (($key,$value) = each %ENV) {
print "$key=$value\en";
}
.fi
See also keys() and values().
.Ip "eof(FILEHANDLE)" 8 8
.Ip "eof()" 8
.Ip "eof" 8
Returns 1 if the next read on FILEHANDLE will return end of file, or if
FILEHANDLE is not open.
FILEHANDLE may be an expression whose value gives the real filehandle name.
(Note that this function actually reads a character and then ungetc's it,
so it is not very useful in an interactive context.)
An eof without an argument returns the eof status for the last file read.
Empty parentheses () may be used to indicate the pseudo file formed of the
files listed on the command line, i.e. eof() is reasonable to use inside
a while (<>) loop to detect the end of only the last file.
Use eof(ARGV) or eof without the parentheses to test EACH file in a while (<>) loop.
Examples:
.nf
.ne 7
# insert dashes just before last line of last file
while (<>) {
if (eof()) {
print "\-\|\-\|\-\|\-\|\-\|\-\|\-\|\-\|\-\|\-\|\-\|\-\|\-\|\-\en";
}
print;
}
.ne 7
# reset line numbering on each input file
while (<>) {
print "$.\et$_";
if (eof) { # Not eof().
close(ARGV);
}
}
.fi
.Ip "eval(EXPR)" 8 6
.Ip "eval EXPR" 8 6
EXPR is parsed and executed as if it were a little
.I perl
program.
It is executed in the context of the current
.I perl
program, so that
any variable settings, subroutine or format definitions remain afterwards.
The value returned is the value of the last expression evaluated, just
as with subroutines.
If there is a syntax error or runtime error, a null string is returned by
eval, and $@ is set to the error message.
If there was no error, $@ is null.
If EXPR is omitted, evaluates $_.
The final semicolon, if any, may be omitted from the expression.
.Sp
Note that, since eval traps otherwise-fatal errors, it is useful for
determining whether a particular feature
(such as dbmopen or symlink) is implemented.
.Ip "exec(LIST)" 8 8
.Ip "exec LIST" 8 6
If there is more than one argument in LIST, or if LIST is an array with
more than one value,
calls execvp() with the arguments in LIST.
If there is only one scalar argument, the argument is checked for shell metacharacters.
If there are any, the entire argument is passed to \*(L"/bin/sh \-c\*(R" for parsing.
If there are none, the argument is split into words and passed directly to
execvp(), which is more efficient.
Note: exec (and system) do not flush your output buffer, so you may need to
set $| to avoid lost output.
Examples:
.nf
exec \'/bin/echo\', \'Your arguments are: \', @ARGV;
exec "sort $outfile | uniq";
.fi
.Sp
If you don't really want to execute the first argument, but want to lie
to the program you are executing about its own name, you can specify
the program you actually want to run by assigning that to a variable and
putting the name of the variable in front of the LIST without a comma.
(This always forces interpretation of the LIST as a multi-valued list, even
if there is only a single scalar in the list.)
Example:
.nf
.ne 2
$shell = '/bin/csh';
exec $shell '-sh'; # pretend it's a login shell
.fi
.Ip "exit(EXPR)" 8 6
.Ip "exit EXPR" 8
Evaluates EXPR and exits immediately with that value.
Example:
.nf
.ne 2
$ans = <STDIN>;
exit 0 \|if \|$ans \|=~ \|/\|^[Xx]\|/\|;
.fi
See also
.IR die .
If EXPR is omitted, exits with 0 status.
.Ip "exp(EXPR)" 8 3
.Ip "exp EXPR" 8
Returns
.I e
to the power of EXPR.
If EXPR is omitted, gives exp($_).
.Ip "fcntl(FILEHANDLE,FUNCTION,SCALAR)" 8 4
Implements the fcntl(2) function.
You'll probably have to say
.nf
require "fcntl.ph"; # probably /usr/local/lib/perl/fcntl.ph
.fi
first to get the correct function definitions.
If fcntl.h doesn't exist or doesn't have the correct definitions
you'll have to roll
your own, based on your C header files such as <sys/fcntl.h>.
(There is a perl script called makelib that comes with the perl kit
which may help you in this.)
Argument processing and value return works just like ioctl below.
Note that fcntl will produce a fatal error if used on a machine that doesn't implement
fcntl(2).
.Ip "fileno(FILEHANDLE)" 8 4
.Ip "fileno FILEHANDLE" 8 4
Returns the file descriptor for a filehandle.
Useful for constructing bitmaps for select().
If FILEHANDLE is an expression, the value is taken as the name of
the filehandle.
.Ip "flock(FILEHANDLE,OPERATION)" 8 4
Calls flock(2) on FILEHANDLE.
See manual page for flock(2) for definition of OPERATION.
Will produce a fatal error if used on a machine that doesn't implement
flock(2).
Here's a mailbox appender for BSD systems.
.nf
.ne 20
$LOCK_SH = 1;
$LOCK_EX = 2;
$LOCK_NB = 4;
$LOCK_UN = 8;
sub lock {
flock(MBOX,$LOCK_EX);
# and, in case someone appended
# while we were waiting...
seek(MBOX, 0, 2);
}
sub unlock {
flock(MBOX,$LOCK_UN);
}
open(MBOX, ">>/usr/spool/mail/$ENV{'USER'}")
|| die "Can't open mailbox: $!";
do lock();
print MBOX $msg,"\en\en";
do unlock();
.fi
.Ip "fork" 8 4
Does a fork() call.
Returns the child pid to the parent process and 0 to the child process.
Note: unflushed buffers remain unflushed in both processes, which means
you may need to set $| to avoid duplicate output.
.Ip "getc(FILEHANDLE)" 8 4
.Ip "getc FILEHANDLE" 8
.Ip "getc" 8
Returns the next character from the input file attached to FILEHANDLE, or
a null string at EOF.
If FILEHANDLE is omitted, reads from STDIN.
.Ip "getlogin" 8 3
Returns the current login from /etc/utmp, if any.
If null, use getpwuid.
$login = getlogin || (getpwuid($<))[0] || "Somebody";
.Ip "getpeername(SOCKET)" 8 3
Returns the packed sockaddr address of other end of the SOCKET connection.
.nf
.ne 4
# An internet sockaddr
$sockaddr = 'S n a4 x8';
$hersockaddr = getpeername(S);
.ie t \{\
($family, $port, $heraddr) = unpack($sockaddr,$hersockaddr);
'br\}
.el \{\
($family, $port, $heraddr) =
unpack($sockaddr,$hersockaddr);
'br\}
.fi
.Ip "getpgrp(PID)" 8 4
.Ip "getpgrp PID" 8
Returns the current process group for the specified PID, 0 for the current
process.
Will produce a fatal error if used on a machine that doesn't implement
getpgrp(2).
If EXPR is omitted, returns process group of current process.
.Ip "getppid" 8 4
Returns the process id of the parent process.
.Ip "getpriority(WHICH,WHO)" 8 4
Returns the current priority for a process, a process group, or a user.
(See getpriority(2).)
Will produce a fatal error if used on a machine that doesn't implement
getpriority(2).
.Ip "getpwnam(NAME)" 8
.Ip "getgrnam(NAME)" 8
.Ip "gethostbyname(NAME)" 8
.Ip "getnetbyname(NAME)" 8
.Ip "getprotobyname(NAME)" 8
.Ip "getpwuid(UID)" 8
.Ip "getgrgid(GID)" 8
.Ip "getservbyname(NAME,PROTO)" 8
.Ip "gethostbyaddr(ADDR,ADDRTYPE)" 8
.Ip "getnetbyaddr(ADDR,ADDRTYPE)" 8
.Ip "getprotobynumber(NUMBER)" 8
.Ip "getservbyport(PORT,PROTO)" 8
.Ip "getpwent" 8
.Ip "getgrent" 8
.Ip "gethostent" 8
.Ip "getnetent" 8
.Ip "getprotoent" 8
.Ip "getservent" 8
.Ip "setpwent" 8
.Ip "setgrent" 8
.Ip "sethostent(STAYOPEN)" 8
.Ip "setnetent(STAYOPEN)" 8
.Ip "setprotoent(STAYOPEN)" 8
.Ip "setservent(STAYOPEN)" 8
.Ip "endpwent" 8
.Ip "endgrent" 8
.Ip "endhostent" 8
.Ip "endnetent" 8
.Ip "endprotoent" 8
.Ip "endservent" 8
These routines perform the same functions as their counterparts in the
system library.
The return values from the various get routines are as follows:
.nf
($name,$passwd,$uid,$gid,
$quota,$comment,$gcos,$dir,$shell) = getpw.\|.\|.
($name,$passwd,$gid,$members) = getgr.\|.\|.
($name,$aliases,$addrtype,$length,@addrs) = gethost.\|.\|.
($name,$aliases,$addrtype,$net) = getnet.\|.\|.
($name,$aliases,$proto) = getproto.\|.\|.
($name,$aliases,$port,$proto) = getserv.\|.\|.
.fi
The $members value returned by getgr.\|.\|. is a space separated list
of the login names of the members of the group.
.Sp
The @addrs value returned by the gethost.\|.\|. functions is a list of the
raw addresses returned by the corresponding system library call.
In the Internet domain, each address is four bytes long and you can unpack
it by saying something like:
.nf
($a,$b,$c,$d) = unpack('C4',$addr[0]);
.fi
.Ip "getsockname(SOCKET)" 8 3
Returns the packed sockaddr address of this end of the SOCKET connection.
.nf
.ne 4
# An internet sockaddr
$sockaddr = 'S n a4 x8';
$mysockaddr = getsockname(S);
.ie t \{\
($family, $port, $myaddr) = unpack($sockaddr,$mysockaddr);
'br\}
.el \{\
($family, $port, $myaddr) =
unpack($sockaddr,$mysockaddr);
'br\}
.fi
.Ip "getsockopt(SOCKET,LEVEL,OPTNAME)" 8 3
Returns the socket option requested, or undefined if there is an error.
.Ip "gmtime(EXPR)" 8 4
.Ip "gmtime EXPR" 8
Converts a time as returned by the time function to a 9-element array with
the time analyzed for the Greenwich timezone.
Typically used as follows:
.nf
.ne 3
.ie t \{\
($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time);
'br\}
.el \{\
($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
gmtime(time);
'br\}
.fi
All array elements are numeric, and come straight out of a struct tm.
In particular this means that $mon has the range 0.\|.11 and $wday has the
range 0.\|.6.
If EXPR is omitted, does gmtime(time).
.Ip "goto LABEL" 8 6
Finds the statement labeled with LABEL and resumes execution there.
Currently you may only go to statements in the main body of the program
that are not nested inside a do {} construct.
This statement is not implemented very efficiently, and is here only to make
the
.IR sed -to- perl
translator easier.
I may change its semantics at any time, consistent with support for translated
.I sed
scripts.
Use it at your own risk.
Better yet, don't use it at all.
.Ip "grep(EXPR,LIST)" 8 4
Evaluates EXPR for each element of LIST (locally setting $_ to each element)
and returns the array value consisting of those elements for which the
expression evaluated to true.
In a scalar context, returns the number of times the expression was true.
.nf
@foo = grep(!/^#/, @bar); # weed out comments
.fi
Note that, since $_ is a reference into the array value, it can be
used to modify the elements of the array.
While this is useful and supported, it can cause bizarre results if
the LIST is not a named array.
.Ip "hex(EXPR)" 8 4
.Ip "hex EXPR" 8
Returns the decimal value of EXPR interpreted as an hex string.
(To interpret strings that might start with 0 or 0x see oct().)
If EXPR is omitted, uses $_.
.Ip "index(STR,SUBSTR,POSITION)" 8 4
.Ip "index(STR,SUBSTR)" 8 4
Returns the position of the first occurrence of SUBSTR in STR at or after
POSITION.
If POSITION is omitted, starts searching from the beginning of the string.
The return value is based at 0, or whatever you've
set the $[ variable to.
If the substring is not found, returns one less than the base, ordinarily \-1.
.Ip "int(EXPR)" 8 4
.Ip "int EXPR" 8
Returns the integer portion of EXPR.
If EXPR is omitted, uses $_.
.Ip "ioctl(FILEHANDLE,FUNCTION,SCALAR)" 8 4
Implements the ioctl(2) function.
You'll probably have to say
.nf
require "ioctl.ph"; # probably /usr/local/lib/perl/ioctl.ph
.fi
first to get the correct function definitions.
If ioctl.h doesn't exist or doesn't have the correct definitions
you'll have to roll
your own, based on your C header files such as <sys/ioctl.h>.
(There is a perl script called makelib that comes with the perl kit
which may help you in this.)
SCALAR will be read and/or written depending on the FUNCTION\*(--a pointer
to the string value of SCALAR will be passed as the third argument of
the actual ioctl call.
(If SCALAR has no string value but does have a numeric value, that value
will be passed rather than a pointer to the string value.
To guarantee this to be true, add a 0 to the scalar before using it.)
The pack() and unpack() functions are useful for manipulating the values
of structures used by ioctl().
The following example sets the erase character to DEL.
.nf
.ne 9
require 'ioctl.ph';
$sgttyb_t = "ccccs"; # 4 chars and a short
if (ioctl(STDIN,$TIOCGETP,$sgttyb)) {
@ary = unpack($sgttyb_t,$sgttyb);
$ary[2] = 127;
$sgttyb = pack($sgttyb_t,@ary);
ioctl(STDIN,$TIOCSETP,$sgttyb)
|| die "Can't ioctl: $!";
}
.fi
The return value of ioctl (and fcntl) is as follows:
.nf
.ne 4
if OS returns:\h'|3i'perl returns:
-1\h'|3i' undefined value
0\h'|3i' string "0 but true"
anything else\h'|3i' that number
.fi
Thus perl returns true on success and false on failure, yet you can still
easily determine the actual value returned by the operating system:
.nf
($retval = ioctl(...)) || ($retval = -1);
printf "System returned %d\en", $retval;
.fi
.Ip "join(EXPR,LIST)" 8 8
.Ip "join(EXPR,ARRAY)" 8
Joins the separate strings of LIST or ARRAY into a single string with fields
separated by the value of EXPR, and returns the string.
Example:
.nf
.ie t \{\
$_ = join(\|\':\', $login,$passwd,$uid,$gid,$gcos,$home,$shell);
'br\}
.el \{\
$_ = join(\|\':\',
$login,$passwd,$uid,$gid,$gcos,$home,$shell);
'br\}
.fi
See
.IR split .
.Ip "keys(ASSOC_ARRAY)" 8 6
.Ip "keys ASSOC_ARRAY" 8
Returns a normal array consisting of all the keys of the named associative
array.
The keys are returned in an apparently random order, but it is the same order
as either the values() or each() function produces (given that the associative array
has not been modified).
Here is yet another way to print your environment:
.nf
.ne 5
@keys = keys %ENV;
@values = values %ENV;
while ($#keys >= 0) {
print pop(keys), \'=\', pop(values), "\en";
}
or how about sorted by key:
.ne 3
foreach $key (sort(keys %ENV)) {
print $key, \'=\', $ENV{$key}, "\en";
}
.fi
.Ip "kill(LIST)" 8 8
.Ip "kill LIST" 8 2
Sends a signal to a list of processes.
The first element of the list must be the signal to send.
Returns the number of processes successfully signaled.
.nf
$cnt = kill 1, $child1, $child2;
kill 9, @goners;
.fi
If the signal is negative, kills process groups instead of processes.
(On System V, a negative \fIprocess\fR number will also kill process groups,
but that's not portable.)
You may use a signal name in quotes.
.Ip "last LABEL" 8 8
.Ip "last" 8
The
.I last
command is like the
.I break
statement in C (as used in loops); it immediately exits the loop in question.
If the LABEL is omitted, the command refers to the innermost enclosing loop.
The
.I continue
block, if any, is not executed:
.nf
.ne 4
line: while (<STDIN>) {
last line if /\|^$/; # exit when done with header
.\|.\|.
}
.fi
.Ip "length(EXPR)" 8 4
.Ip "length EXPR" 8
Returns the length in characters of the value of EXPR.
If EXPR is omitted, returns length of $_.
.Ip "link(OLDFILE,NEWFILE)" 8 2
Creates a new filename linked to the old filename.
Returns 1 for success, 0 otherwise.
.Ip "listen(SOCKET,QUEUESIZE)" 8 2
Does the same thing that the listen system call does.
Returns true if it succeeded, false otherwise.
See example in section on Interprocess Communication.
.Ip "local(LIST)" 8 4
Declares the listed variables to be local to the enclosing block,
subroutine, eval or \*(L"do\*(R".
All the listed elements must be legal lvalues.
This operator works by saving the current values of those variables in LIST
on a hidden stack and restoring them upon exiting the block, subroutine or eval.
This means that called subroutines can also reference the local variable,
but not the global one.
The LIST may be assigned to if desired, which allows you to initialize
your local variables.
(If no initializer is given for a particular variable, it is created with
an undefined value.)
Commonly this is used to name the parameters to a subroutine.
Examples:
.nf
.ne 13
sub RANGEVAL {
local($min, $max, $thunk) = @_;
local($result) = \'\';
local($i);
# Presumably $thunk makes reference to $i
for ($i = $min; $i < $max; $i++) {
$result .= eval $thunk;
}
$result;
}
.ne 6
if ($sw eq \'-v\') {
# init local array with global array
local(@ARGV) = @ARGV;
unshift(@ARGV,\'echo\');
system @ARGV;
}
# @ARGV restored
.ne 6
# temporarily add to digits associative array
if ($base12) {
# (NOTE: not claiming this is efficient!)
local(%digits) = (%digits,'t',10,'e',11);
do parse_num();
}
.fi
Note that local() is a run-time command, and so gets executed every time
through a loop, using up more stack storage each time until it's all
released at once when the loop is exited.
.Ip "localtime(EXPR)" 8 4
.Ip "localtime EXPR" 8
Converts a time as returned by the time function to a 9-element array with
the time analyzed for the local timezone.
Typically used as follows:
.nf
.ne 3
.ie t \{\
($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
'br\}
.el \{\
($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
localtime(time);
'br\}
.fi
All array elements are numeric, and come straight out of a struct tm.
In particular this means that $mon has the range 0.\|.11 and $wday has the
range 0.\|.6.
If EXPR is omitted, does localtime(time).
.Ip "log(EXPR)" 8 4
.Ip "log EXPR" 8
Returns logarithm (base
.IR e )
of EXPR.
If EXPR is omitted, returns log of $_.
.Ip "lstat(FILEHANDLE)" 8 6
.Ip "lstat FILEHANDLE" 8
.Ip "lstat(EXPR)" 8
.Ip "lstat SCALARVARIABLE" 8
Does the same thing as the stat() function, but stats a symbolic link
instead of the file the symbolic link points to.
If symbolic links are unimplemented on your system, a normal stat is done.
.Ip "m/PATTERN/io" 8 4
.Ip "/PATTERN/io" 8
Searches a string for a pattern match, and returns true (1) or false (\'\').
If no string is specified via the =~ or !~ operator,
the $_ string is searched.
(The string specified with =~ need not be an lvalue\*(--it may be the result of an expression evaluation, but remember the =~ binds rather tightly.)
See also the section on regular expressions.
.Sp
If / is the delimiter then the initial \*(L'm\*(R' is optional.
With the \*(L'm\*(R' you can use any pair of non-alphanumeric characters
as delimiters.
This is particularly useful for matching Unix path names that contain \*(L'/\*(R'.
If the final delimiter is followed by the optional letter \*(L'i\*(R', the matching is
done in a case-insensitive manner.
PATTERN may contain references to scalar variables, which will be interpolated
(and the pattern recompiled) every time the pattern search is evaluated.
(Note that $) and $| may not be interpolated because they look like end-of-string tests.)
If you want such a pattern to be compiled only once, add an \*(L"o\*(R" after
the trailing delimiter.
This avoids expensive run-time recompilations, and
is useful when the value you are interpolating won't change over the
life of the script.
.Sp
If used in a context that requires an array value, a pattern match returns an
array consisting of the subexpressions matched by the parentheses in the
pattern,
i.e. ($1, $2, $3.\|.\|.).
It does NOT actually set $1, $2, etc. in this case, nor does it set $+, $`, $&
or $'.
If the match fails, a null array is returned.
If the match succeeds, but there were no parentheses, an array value of (1)
is returned.
.Sp
Examples:
.nf
.ne 4
open(tty, \'/dev/tty\');
<tty> \|=~ \|/\|^y\|/i \|&& \|do foo(\|); # do foo if desired
if (/Version: \|*\|([0\-9.]*\|)\|/\|) { $version = $1; }
next if m#^/usr/spool/uucp#;
.ne 5
# poor man's grep
$arg = shift;
while (<>) {
print if /$arg/o; # compile only once
}
if (($F1, $F2, $Etc) = ($foo =~ /^(\eS+)\es+(\eS+)\es*(.*)/))
.fi
This last example splits $foo into the first two words and the remainder
of the line, and assigns those three fields to $F1, $F2 and $Etc.
The conditional is true if any variables were assigned, i.e. if the pattern
matched.
.Ip "mkdir(FILENAME,MODE)" 8 3
Creates the directory specified by FILENAME, with permissions specified by
MODE (as modified by umask).
If it succeeds it returns 1, otherwise it returns 0 and sets $! (errno).
.Ip "msgctl(ID,CMD,ARG)" 8 4
Calls the System V IPC function msgctl. If CMD is &IPC_STAT, then ARG
must be a variable which will hold the returned msqid_ds structure.
Returns like ioctl: the undefined value for error, "0 but true" for
zero, or the actual return value otherwise.
.Ip "msgget(KEY,FLAGS)" 8 4
Calls the System V IPC function msgget. Returns the message queue id,
or the undefined value if there is an error.
.Ip "msgsnd(ID,MSG,FLAGS)" 8 4
Calls the System V IPC function msgsnd to send the message MSG to the
message queue ID. MSG must begin with the long integer message type,
which may be created with pack("L", $type). Returns true if
successful, or false if there is an error.
.Ip "msgrcv(ID,VAR,SIZE,TYPE,FLAGS)" 8 4
Calls the System V IPC function msgrcv to receive a message from
message queue ID into variable VAR with a maximum message size of
SIZE. Note that if a message is received, the message type will be
the first thing in VAR, and the maximum length of VAR is SIZE plus the
size of the message type. Returns true if successful, or false if
there is an error.
|