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

📄 perl.ms

📁 早期freebsd实现
💻 MS
📖 第 1 页 / 共 5 页
字号:
declaration, and returns the valueof 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 subroutineexists.)If you pass arrays as part of LIST you may wish to pass the lengthof the array in front of each array.(See the section on subroutines later on.)The parentheses are required to avoid confusion with the \*(L"do EXPR\*(R"form..SpSUBROUTINE may also be a single scalar variable, in which casethe name of the subroutine to execute is taken from the variable..SpAs an alternate (and preferred) form,you may call a subroutine by prefixing the name withan 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 undefoperators:.nf	if (defined &$var) { &$var($parm); undef &$var; }.fi.Ip "do EXPR" 8 3Uses the value of EXPR as a filename and executes the contents of the fileas a.I perlscript.Its primary use is to include subroutines from a.I perlsubroutine library..nf	do \'stat.pl\';is just like	eval \`cat stat.pl\`;.fiexcept that it's more efficient, more concise, keeps track of the currentfilename for error messages, and searches all the.B \-Ilibraries if the fileisn'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 youcall it, so if you are going to use the file inside a loop you might preferto 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\*(--aworkaround 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.fiNote that inclusion of library routines is better done withthe \*(L"require\*(R" operator..Ip "dump LABEL" 8 6This causes an immediate core dump.Primarily this is so that you can use the undump program to turn yourcore dump into an executable binary after having initialized all yourvariables 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 morewhen the program is reincarnated, with possible resulting confusion on the partof perl.See also \-u..SpExample:.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" 8Returns a 2 element array consisting of the key and value for the nextvalue 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 whenassigned 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 alleach(), keys() and values() function calls in the program.The following prints out your environment like the printenv program, onlyin a different order:.nf.ne 3	while (($key,$value) = each %ENV) {		print "$key=$value\en";	}.fiSee also keys() and values()..Ip "eof(FILEHANDLE)" 8 8.Ip "eof()" 8.Ip "eof" 8Returns 1 if the next read on FILEHANDLE will return end of file, or ifFILEHANDLE 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 thefiles listed on the command line, i.e. eof() is reasonable to use insidea 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.Ip "eval BLOCK" 8 6EXPR is parsed and executed as if it were a little.I perlprogram.It is executed in the context of the current.I perlprogram, so thatany variable settings, subroutine or format definitions remain afterwards.The value returned is the value of the last expression evaluated, justas with subroutines.If there is a syntax error or runtime error, or a die statement isexecuted, an undefined value is returned byeval, and $@ is set to the error message.If there was no error, $@ is guaranteed to be a null string.If EXPR is omitted, evaluates $_.The final semicolon, if any, may be omitted from the expression..SpNote that, since eval traps otherwise-fatal errors, it is useful fordetermining whether a particular feature(such as dbmopen or symlink) is implemented.It is also Perl's exception trapping mechanism, where the die operator isused to raise exceptions..SpIf the code to be executed doesn't vary, you may usethe eval-BLOCK form to trap run-time errors without incurringthe penalty of recompiling each time.The error, if any, is still returned in $@.Evaluating a single-quoted string (as EXPR) has the same effect, except thatthe eval-EXPR form reports syntax errors at run time via $@, whereas theeval-BLOCK form reports syntax errors at compile time.  The eval-EXPR formis optimized to eval-BLOCK the first time it succeeds.  (Since the replacementside of a substitution is considered a single-quoted string when youuse the e modifier, the same optimization occurs there.)  Examples:.nf.ne 11	# make divide-by-zero non-fatal	eval { $answer = $a / $b; }; warn $@ if $@;	# optimized to same thing after first use	eval '$answer = $a / $b'; warn $@ if $@;	# a compile-time error	eval { $answer = };	# a run-time error	eval '$answer =';	# sets $@.fi.Ip "exec(LIST)" 8 8.Ip "exec LIST" 8 6If there is more than one argument in LIST, or if LIST is an array withmore 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 toexecvp(), which is more efficient.Note: exec (and system) do not flush your output buffer, so you may need toset $| to avoid lost output.Examples:.nf	exec \'/bin/echo\', \'Your arguments are: \', @ARGV;	exec "sort $outfile | uniq";.fi.SpIf you don't really want to execute the first argument, but want to lieto the program you are executing about its own name, you can specifythe program you actually want to run by assigning that to a variable andputting 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, evenif 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" 8Evaluates EXPR and exits immediately with that value.Example:.nf.ne 2	$ans = <STDIN>;	exit 0 \|if \|$ans \|=~ \|/\|^[Xx]\|/\|;.fiSee also.IR die .If EXPR is omitted, exits with 0 status..Ip "exp(EXPR)" 8 3.Ip "exp EXPR" 8Returns.I eto the power of EXPR.If EXPR is omitted, gives exp($_)..Ip "fcntl(FILEHANDLE,FUNCTION,SCALAR)" 8 4Implements the fcntl(2) function.You'll probably have to say.nf	require "fcntl.ph";	# probably /usr/local/lib/perl/fcntl.ph.fifirst to get the correct function definitions.If fcntl.ph doesn't exist or doesn't have the correct definitionsyou'll have to rollyour own, based on your C header files such as <sys/fcntl.h>.(There is a perl script called h2ph that comes with the perl kitwhich 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 implementfcntl(2)..Ip "fileno(FILEHANDLE)" 8 4.Ip "fileno FILEHANDLE" 8 4Returns the file descriptor for a filehandle.Useful for constructing bitmaps for select().If FILEHANDLE is an expression, the value is taken as the name ofthe filehandle..Ip "flock(FILEHANDLE,OPERATION)" 8 4Calls flock(2) on FILEHANDLE.See manual page for flock(2) for definition of OPERATION.Returns true for success, false on failure.Will produce a fatal error if used on a machine that doesn't implementflock(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 4Does 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 meansyou may need to set $| to avoid duplicate output..Ip "getc(FILEHANDLE)" 8 4.Ip "getc FILEHANDLE" 8.Ip "getc" 8Returns the next character from the input file attached to FILEHANDLE, ora null string at EOF.If FILEHANDLE is omitted, reads from STDIN..Ip "getlogin" 8 3Returns the current login from /etc/utmp, if any.If null, use getpwuid.	$login = getlogin || (getpwuid($<))[0] || "Somebody";.Ip "getpeername(SOCKET)" 8 3Returns 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" 8Returns the current process group for the specified PID, 0 for the currentprocess.Will produce a fatal error if used on a machine that doesn't implementgetpgrp(2).If EXPR is omitted, returns process group of current process..Ip "getppid" 8 4Returns the process id of the parent process..Ip "getpriority(WHICH,WHO)" 8 4Returns 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 implementgetpriority(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" 8These routines perform the same functions as their counterparts in thesystem library.Within an array context,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(If the entry doesn't exist you get a nul

⌨️ 快捷键说明

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