跳转到内容

Perl 编程/函数参考

来自 Wikibooks,开放世界中的开放书籍
上一个: 概念索引 索引 下一个: 关键字

字符串函数

[编辑 | 编辑源代码]

仅当字符串中的最后一个字符被识别为记录分隔符(例如换行符)时,才删除字符串中的最后一个字符。

返回值

[编辑 | 编辑源代码]

?

chomp($String = $_);

chomp; # removes the last character from $_ if it is a record separator
chomp(); # (same)
chomp($String); # removes the last character from $String if it is a record separator

另请参阅

[编辑 | 编辑源代码]
  • chop - 从字符串中删除最后一个字符

无论如何,从字符串中删除最后一个字符。

返回值

[编辑 | 编辑源代码]

?

chop($String = $_);

chop; # removes the last character from $_
chop(); # (same)
chop($String); # removes the last character from $String

另请参阅

[编辑 | 编辑源代码]
  • chomp - 如果字符串中的最后一个字符是记录分隔符,则从字符串中删除最后一个字符。

从字符串中删除最后一个字符(例如,从文件中读取时删除换行符)。

print chr(65);  # Prints a capital A

获取 ASCII 字符,给出它的代码。

# One-way hash function
my $HashedWord = crypt($Word, $Salt);

(另请参阅 MD5 )

盐字符串只需要两位长,它提供了一种随机化哈希的方法,这样即使同一个单词,如果使用不同的 $Salt; 值,也可以产生几个不同的哈希!

print hex(11);  # Prints B

将数字转换为十六进制。

反过来 - 将十六进制转换为数字:print hex(11); # 打印 17

您可以使用

print sprintf("%X",11); # 打印 B

在一个字符串中搜索另一个字符串(请参阅 rindex 以从末尾到开头搜索)。

$Result = index($Haystack, $Needle);
$Result = index($Haystack, $Needle, $StartPosition);
index("Some text", "bleh"); # Returns -1 (not found)
index("Some text", "Some"); # Returns 0 (first character)
index("Some text", "text"); # Returns 5 (sixth character)

特殊变量 $[ 始终添加到返回值中,但 $[ 通常为 0,并且手册建议将其保留为 0。

$Lowercase = lc($String);

将字符串转换为小写。

将字符串的第一个字符转换为小写。

print "String is " . length($String) . " characters long\n";

返回字符串的长度。

print oct(8);  # Prints 10

将数字转换为八进制。

将字符转换为其数字。

print ord("A"); # prints 65

接受一个列表,并使用提供的规则集将其转换为字符串。

my $String = pack($Template, @ListOfNumbers);
my $String = pack("CCCC",65,66,67,68); # Result: "ABCD"

$Template 可以由以下组成

   a	A string with arbitrary binary data, will be null padded.
   A	An ascii string, will be space padded.
   Z	A null terminated (asciz) string, will be null padded.
   b	A bit string (ascending bit order inside each byte, like vec()).
   B	A bit string (descending bit order inside each byte).
   h	A hex string (low nybble first).
   H	A hex string (high nybble first).
   c	A signed char value.
   C	An unsigned char value. Only does bytes. See U for Unicode.
   s	A signed short value.
   S	An unsigned short value. (Exactly 16 bits unless you use the ! suffix)
   i	A signed integer value.
   I	An unsigned integer value. (At least 32 bits wide, machine-dependent)
   l	A signed long value.
   L	An unsigned long value. (Exactly 32 bits unless you use the ! suffix)
   n	An unsigned short in "network" (big-endian) order.
   N	An unsigned long in "network" (big-endian) order.
   v	An unsigned short in "VAX" (little-endian) order.
   V	An unsigned long in "VAX" (little-endian) order. (Exactly 16 bits and 32 bits respectively)
   q	A signed quad (64-bit) value.
   Q	An unsigned quad value. (Only available if your system supports 64-bit integers and Perl has been compiled to support them)
   f	A single-precision float in the native format.
   d	A double-precision float in the native format.
   p	A pointer to a null-terminated string.
   P	A pointer to a structure (fixed-length string).
   u	A uuencoded string.
   U	A Unicode character number. Encodes to UTF-8 internally.
   w	A BER compressed integer. Its bytes represent an unsigned integer in base 128, most significant digit first, with as few digits as possible. Bit eight (the high bit) is set on each byte except the last.
   x	A null byte.
   X	Back up a byte.
   @	Null fill to absolute position.

每个字母后可以选择跟一个数字,表示重复次数。

整数类型 sSlL 可以紧跟 ! 后缀,表示本机短整型或长整型。

反转字符串(在标量上下文中)或列表(在列表上下文中)。

my @ReversedList = reverse(@List);
# As commonly seen in Perl programs:
foreach( reverse( sort( @List )))
{
...
}
my $ReversedString = reverse($String);
my @List = ("One ", "two ", "three...");
my $ReversedListAsString = reverse(@List); # Prints "...eerht owt enO"

从字符串的末尾开始,在一个字符串中搜索另一个字符串。

$Result = rindex($Haystack, $Needle);
$Result = rindex($Haystack, $Needle, $StartPosition);
rindex("Some text", "bleh"); # Returns -1 (not found)
rindex("Some text", "Some"); # Returns 0 (first character)
rindex("abbbbb", "b");       # Returns 5 (first "b" found, when starting at the end)

打印格式化字符串

my $Text = sprintf("%d/%d is %08.5f", 1, 3, 1/3); # Result: "10/3 is 003.33333"
sprintf("Character: %c", 65);
sprintf("String %s", "Hello");
sprintf("Signed integer: %d", 15);
sprintf("Unsigned integer: %u", 15);
sprintf("Unsigned int (in octal): %o", 15);
sprintf("Unisgned int (in hex): %x", 15);      # Use %X to get upper-case output
sprintf("Binary number: %b", 15);
sprintf("Scientific notation: %e", 5000);      # Use %E to get upper-case output
sprintf("Floating point number: %f", 1/3);     # 0.3333333
sprintf("Floating point number: %g", 1/3);     # Decides between scientific and float. %G is uppercase
sprintf("Pointer: %p", $Variable);

使用 %% 获取百分号。

使用 %n 请求到目前为止写入的字符数,并将它放入列表中的下一个变量中。您可能需要检查用户提供的格式化规则中是否包含此代码。

sprintf("%02d", $Minutes);  # Forces leading zeros to make the string two characters long
sprintf("%1.5f", $Number);  # Limits the number of decimal places

返回字符串的一部分(一个子字符串

格式:substr string start-position length

start-position 从零开始。
负数从字符串末尾开始。
$FirstLetter   = substr($Text, 0, 1);   # First letter
$First3Letters = substr($Text, 0, 3);   # First three letters
$Last3Letters  = substr($Text, -3);     # Last three letters

您可以在赋值语句的左侧使用substr 来更改字符串的一部分。这实际上可以缩短或加长字符串。

 $text = 'cat dog';
 substr ($mystring, 3, 1) = ' and ';  # $text now contains 'cat and dog'
$Uppercase = uc($String);

将字符串转换为大写

将字符串的第一个字符转换为大写

数值函数

[编辑 | 编辑源代码]

返回数字的绝对(正)值

$Number = abs(-100); # Returns 100;
# Converts cartesian(x,y) coordinates into an angle
$Number = atan2($Y, $X);
# Returns the cosine of an angle (radians)
$Number = cos($Angle);  # Cosine = Adjacent/Hypotenuse
# Raises e to a specified power
$Number = exp(2); # Returns e^2
e ≈ 2.71828183 more about e
# Interprets a string as hexidecimal, and returns its value
$Number = hex("10"); # Returns 16
$Number = hex("0xFF"); # Returns 255

将数字向零方向取整,返回一个整数

$Number = int(-1.6);  # Returns -1
$Number = int(0.9);   # Returns 0
$Number = int(28.54); # Returns 28
# Returns the natural logarithm of a number
$Number = log(2.71828183);   # Returns 1
$Number = exp(log($X));      # Returns $X
$Number = log($X)/log(10);   # Returns log10($X). Alternately, you can use the log10() function in the POSIX module
$Number = log($X)/log(15);   # Returns log to the base 15 of $X
# Interprets a string as octal, and returns its value
$Number = oct("10"); # Returns 8
$Number = oct("21"); # Returns 17
# Gets a random number (may automatically call srand() if that's not been done)
$Number = rand();  # Returns a random number from 0 to 1
$Number = int(rand(800));  # Returns a random integer from 0 to 799
$Number = 1 + int(rand(999));  # Returns a random integer from 1 to 999
# Returns the sine of an angle (radians)
$Number = sin($Angle);  # Sine = Opposite/Hypotenuse
# Returns the square-root of a number
$Number = sqrt(4);                  # Returns 2
$Number = sqrt($X ** 2 + $Y ** 2);  # Returns the diagonal distance across a $X x $Y rectangle

如果您需要对负数求根,请参见Math::Complex 模块。

# Seeds (sets-up) the random-number generator
srand();

版本相关,并且不能保证旧版本的 Perl 具有良好的种子值。有关更多可能性,请参见Math::TrulyRandom 模块。当前版本的 Perl 使用 urandom 设备(如果可用)。

数组函数

[编辑 | 编辑源代码]
$LastElement = pop(@MyArray);

从数组中取出最后一个元素。

push(@MyArray, "Last element");
push(@MyArray, "several", "more", "elements");

将元素列表推送到数组的末尾。

shift(@MyArray); # Delete the first element
$FirstElement = shift(@MyArray); # Delete the first element, load it into $FirstElement instead

从数组中取出第一个元素。

# Removes elements from an array, optionally replacing them with a new array
splice(@Array); # Removes all elements from array
splice(@Array, 10); # Removes from element 10 to the end of the array
splice(@Array, -10); # Removes the last 10 elements of the array
splice(@Array, 0, 10); # Removes the first 10 elements of the array
@NewArray = splice(@Array, 0, 10); # Removes the first 10 elements of the array and returns those 10 items
splice(@Array, 0, 10, @Array2); # Replaces the first 10 elements of the array with Array2
unshift(@MyArray, "New element");
unshift(@MyArray, "several", "more", "elements");

将元素列表添加到数组的开头。

列表函数

[编辑 | 编辑源代码]
# Returns a list of elements for which an expression is true
@TextFiles = grep(/\.txt$/, @AllFiles);
$NumberOfTextFiles = grep(/\.txt$/, @AllFiles);
# Can use a block of code instead of an expression
@TextFiles = grep({return(substr($_, -3) eq "txt");}, @AllFiles);
# Joins the items of a list into a single string
$OneItemPerLine = join( "\n", @List);
$EverythingBunchedTogether = join( "", @List);
$Filename = join( "/", ($Directory, $Subdirectory, $Filename));
# Evaluates a block of code for each item in a list, and returns
# a list of the results
@UppercaseList = map(uc, @List);
@Numbers = map {"Number $_"} 1..100;
# Reverses the order of a list
@ReversedList = reverse(@List);
# In scalar context, concatenates the list and then reverses the string
$ReversedString = reverse('foo','bar','baz'); # gives 'zabraboof'
# Sorts the elements in a list
@AsciiSort = sort(@RandomList);
@AsciiSort = sort @RandomList;
foreach $Item (sort @RandomList)
  {...}
# Can specify a function to decide the sort order
@CaseInsensitiveSort = sort {uc($a) cmp uc($b)} @RandomList;
@NumericSort = sort {$a <=> $b} @RandomList;
@CustomSort = sort custom_function_name @RandomList;

将字符串解包到列表中 - 有关详细信息,请参见 pack() 函数的可用模板

关联数组函数

[编辑 | 编辑源代码]
# Remove an element from a hash
%h = ('a'=>1, 'cow'=>'moo', 'b'=>2);
delete $h{cow};
# %h now contains ('a'=>1, 'b'=>2)
# Return the 'next' key/value pair (in a random order)
while (($key, $value) = each (%hash)) {
   print "$key => $value\n";
}
 # Tests whether or not a key exists in a hash (even if the value for that key is undef)
 if (exists $hash{$key}) {
   print "\%hash contains a value for key '$key'\n";
 }
 # Returns a list of all keys from the hash, in same 'random' order as each
 foreach $key (keys %hash) {
   print "$key => $hash{$key}\n";
 }
 # Returns a list of all values from the hash, in same 'random' order as keys
 foreach $value (values %hash) {
   print "\%hash contains a value '$value'\n";
 }

输入和输出函数

[编辑 | 编辑源代码]
# closes a filehandle when it is no longer needed
close(STDERR); # hide debugging info from the user
# Close a directory open by opendir
closedir(DIRHANDLE);


退出程序,向 "STDERR" 打印第一个参数以及当前文件和行号。用于捕获错误。

 die "Error: $!\n" unless chdir '/';
eof FILEHANDLE
eof()
eof

如果对 FILEHANDLE 的下一次读取将返回文件结束符,或者 FILEHANDLE 未打开,则此函数返回 trueFILEHANDLE 可以是表达式,其值给出实际的文件句柄,或者是对某种文件句柄对象的引用。没有参数的 eof 返回最后读取文件的结束符状态。带空括号 ()eof() 测试 ARGV 文件句柄(最常见的是 <> 中的空文件句柄)。因此,在 while (<>) 循环中,带括号的 eof() 将仅检测一组文件的最后一个文件的结束。使用 eof(不带括号)来测试 while (<>) 循环中的每个文件。例如,以下代码在最后一个文件的最后一行之前插入破折号

while (<>) {
    if (eof()) {
        print "-" x 30, "\n";
    }
    print;
}

另一方面,此脚本会重置每个输入文件的行号

# reset line numbering on each input file
while (<>) {
    next if /^\s*#/;        # skip comments
    print "$.\t$_";
} continue {
    close ARGV if eof;      # Not eof()!
}

与 sed 程序中的 "$" 一样,eof 往往出现在行号范围内。以下脚本打印从 /pattern/ 到每个输入文件末尾的行

while (<>) {
    print if /pattern/ .. eof;
}

在这里,翻转操作符 (..) 对每行计算模式匹配。在模式匹配之前,操作符返回 false。当它最终匹配时,操作符开始返回 true,从而导致打印这些行。当 eof 操作符最终返回 true(在正在检查的文件末尾时),翻转操作符重置,并开始对 @ARGV 中的下一个文件再次返回 false

打印给定的参数。

在以下部分中讨论

字符串部分中的关于 print 的旁注

rewinddir

[编辑 | 编辑源代码]

用于处理定长记录的函数

[编辑 | 编辑源代码]

参见页面上方的pack条目

# Reads data from a file-handle
read(FILEHANDLE, $StoreDataHere, $NumberBytes);
# Returns the number of bytes read
$NumberBytesRead = read(FILEHANDLE, $StoreDataHere, $NumberBytes);
# Optional offset is applied when the data is stored (not when reading)
read(FILEHANDLE, $StoreDataHere, $NumberBytes, Offset);
# Runs a system command
syscall( $Command, $Argument1, $Argument2, $Argument3);
# (maximum 14 arguments)
$ReturnValue = syscall($Command);
# See the pack function for details (unpack does the opposite!)
unpack($Template, $BinaryData);

文件系统函数

[编辑 | 编辑源代码]
if (-r	$FullFilename) // File is readable by effective uid/gid.
if (-w	$FullFilename) // File is writable by effective uid/gid.
if (-x	$FullFilename) // File is executable by effective uid/gid.
if (-o	$FullFilename) // File is owned by effective uid.
if (-R	$FullFilename) // File is readable by real uid/gid.
if (-W	$FullFilename) // File is writable by real uid/gid.
if (-X	$FullFilename) // File is executable by real uid/gid.
if (-O	$FullFilename) // File is owned by real uid.
if (-e	$FullFilename) // File exists.
if (-z	$FullFilename) // File has zero size.
if (-s	$FullFilename) // File has nonzero size (returns size).
if (-f	$FullFilename) // File is a plain file.
if (-d	$FullFilename) // File is a directory.
if (-l	$FullFilename) // File is a symbolic link.
if (-p	$FullFilename) // File is a named pipe (FIFO), or Filehandle is a pipe.
if (-S	$FullFilename) // File is a socket.
if (-b	$FullFilename) // File is a block special file.
if (-c	$FullFilename) // File is a character special file.
if (-t	$FullFilename) // Filehandle is opened to a tty.
if (-u	$FullFilename) // File has setuid bit set.
if (-g	$FullFilename) // File has setgid bit set.
if (-k	$FullFilename) // File has sticky bit set.
if (-T	$FullFilename) // File is an ASCII text file.
if (-B	$FullFilename) // File is a "binary" file (opposite of -T).
$Age = -M $FullFilename; // Age of file in days when script started.
$Age = -A $FullFilename; // Same for access time.
$Age = -C $FullFilename; // Same for inode change time.
chdir $Directory;
chdir $Directory || die("Couldn't change directory");
chmod 0744 $File1;
chmod 0666 $File1, $File2, $File3;
# 0 for octal, at the beginning of a number
        | Owner | Group | Others |
Execute |   4   |   4   |   4    |
Write   |   2   |   2   |   2    |
Read    |   1   |   1   |   1    |
======--+======-+======-+======--+
Total   |       |       |        |
# Change the owner of a file
chown($NewUserID, $NewGroupID, $Filename);
chown($
NewUserID $NewGroupID, $File1, $File2, $File3);
NewUserID, $NewGroupID, $File1, $File2, $File3);
chown($NewUserID, -1, $Filename); # Leave group unchanged
chown(-1, $NewGroupID, $Filename); # Leave user unchanged
chroot $NewRootDirectory;

设置程序的根目录,这样"/"位置将引用指定的目录。

程序必须以 root 身份运行才能成功。

fcntlglob

[编辑 | 编辑源代码]
# Expands filenames, in a shell-like way
my @TextFiles = glob("*.txt");

另请参阅File::Glob

# Creates a link to a file
link($ExistingFile, $LinkLocation);
link($ExistingFile, $LinkLocation) || die("Couldn't create link");

与 stat() 相同,区别在于如果给定文件是符号链接,则统计链接而不是目标。

mkdir $Filename || die("Couldn't create directory");
mkdir $Filename, 0777; # Make directory with particular file-permissions
open(my $FileHandle, $Filename) || die("Couldn't open file");
open(my $fp, "<", $Filename);   # Read from file
open(my $fp, ">", $Filename);   # Write to file
open(my $fp, ">>", $Filename);  # Append to file
open(my $fp, "<$Filename");     # Read from file
open(my $fp, ">$Filename");     # Write to file
open(my $fp, ">>$Filename");    # Append to file
open(my $fp, "<", "./   filename with whitespace   \0");
open(my $fp, "<", "./->filename with reserved characters\0");


open(my $fp, "$Program |");     # Read from the output of another program
open(m myy $fp, "| $Program");     # Write to the input of another program
open(my $fp, "<", "-");         # Read from standard input
open(my $fp, ">", "-");         # Write to standard output
opendir(my $DirHandle, $Directory) || die("Couldn't open directory");
while (my $Filename = readdir $DirHandle) {
  # Do something with $Filename in $Directory
}
closedir($DirHandle);
opendir(DIR, $Directory) || die("Couldn't open directory");
foreach(readdir(DIR)) {
  # Do something with $_ in $Directory
}
closedir(DIR);
# Finds the value of a symbolic link
$LinkTarget = readlink($LinkPosition);
rename $OldFile, $NewFile or die("Couldn't move file");

在非 *nix 操作系统上可能工作方式不同,并且在不同文件系统之间移动时可能根本不起作用。有关更复杂的文件操作,请参见 [[File::Copy]]。

rmdir $Filename || die("Couldn't remove directory");
stat
$DeviceNum    = $FileStatistics[0]; # device number of filesystemcs[0]; # device number of filesystem
$Inode        = $FileStatistics[1]; # inode number
$FileMode     = $FileStatistics[2]; # (type and permissions)
$NumHardLinks = $FileStatistics[3]; # number of (hard) links to the file
$UserID       = $FileStatistics[4]; # numeric user ID
$GroupID      = $FileStatistics[5]; # numeric group ID
$DeviceIdent  = $FileStatistics[6]; # Device identifier (special files only)
$SizeBytes    = $FileStatistics[7];
$AccessTime   = $FileStatistics[8]; # seconds since the epoch
$ModifyTime   = $FileStatistics[9];
$ChangeTime   = $FileStatistics[10];
$BlockSize    = $FileStatistics[11];
$NumBlocks    = $FileStatistics[12];
# Creates a new filename symbolically linked to the old filename
symlink($OldFilename, $NewFilename);
symlink($OldFilename, $NewFilename) || die("Couldn't create symlink");
eval(symlink($OldFilename, $NewFilename));
# Sets or returns the umask for the process.
my $UMask = umask();
umask(0000); # This process can create any type of files
umask(0001); # This process can't create world-readable files
umask(0444); # This process can't create executable files
# Deletes a file
unlink $Filename;
unlink $Filename || die("Couldn't delete file");
unlink $File1, $File2, $File3;
(unlink($File1, $File2, $File3) == 3) || die("Couldn't delete files");
# Updates the modification times of a list of files
my $AccessTime = time();
my $ModificationTime = time();
utime($AccessTime, $ModificationTime, $Filename);
my $NumFilesChanged = utime($AccessTime, $ModificationTime, $File1, $File2, $File3);

程序函数

[编辑 | 编辑源代码]

返回关于当前函数调用堆栈的信息。在标量上下文中,只返回调用当前子例程的包的名称。在列表上下文中,返回包、文件名和行号。在列表上下文中,如果传递了数值参数,则返回几条信息(见下文)。该参数表示在调用堆栈中回溯多少层。

# !/usr/bin/perl
foo();
sub foo {
   $package = caller; # returns 'main'
   ($package, $filename, $line) = caller; # returns 'main', the file name, and 3
   # Line below returns all 10 pieces of info. (Descriptions self-explanatory from variable names)
   ($package, $filename, $line, $subroutine, $hasargs, $wantarray, $evaltext, $is_require, $hints, $bitmask) =
      caller(0);
 }

实际上没有'import'函数。相反,在编写模块时,约定俗成地创建一个名为'import'的子例程,它将模块所需变量或方法填充到当前命名空间中。

如果您的类以'Exporter'模块为基类,则标准'Exporter'模块提供了导入方法。

声明所有后面的行(直到 EOF 或下一个 package 语句)属于给定包的命名空间。

# !/usr/bin/perl
$x = 5;  # sets $main::x
package Foo;
$x = 5;  # sets $Foo::x
sub bar { # defines &Foo::bar
   print "hello world";
}
package Temp;
$x = 5; # sets $Temp::x

将指定模块的代码包含到当前程序中。模块可以用绝对路径或相对路径指定,也可以用裸词指定。如果给定裸词,则添加'.pm'扩展名,并且'::'被替换为当前操作系统的路径分隔符

require Foo::Bar;
# identical to:
require 'Foo/Bar.pm';

在编译时要求并导入给定模块或pragma。行

use Foo qw/bar baz/;

等同于

BEGIN {
   require Foo;
   import Foo qw/bar baz/;
}

杂项函数

[编辑 | 编辑源代码]
# returns true, if argument is not undef
$x = 0;
print "X defined\n" if defined $x; # prints
print "Y defined\n" if defined $y; # does not print
eval('$a = 30; $b = 40;');
print $a, $b;
# assigns temporary value to global variable for duration of lexical scope
$x = 5;
print "x = $x\n"; # 5
{
  local $x = 10;
  print "x = $x\n"; # 10
}
print "x = $x\n"; # 5
# creates new lexical (ie, not global) variable
$x = 5;  # refers to $main::x
{
  my $x = 10;
  print "x = $x\n"; # the lexical - 10
  print "main's x = $main::x\n" # the global - 5
}
print "x = $x\n";  # the global, because no lexical in scope - 5
# resets hash's internal pointer, to affect lists returned by each
while ($k, $v = each %h) {
  print "$k = $v\n";
  last if ($i++ == 2);
}
# if another each done here, $k,$v will pick up where they left off.
reset %h
# now each will restart from the beginning.
# forces scalar context on an array
@sizes = (scalar @foo, scalar @bar);
# creates a list of the sizes of @foo and @bar, rather than the elements in @foo and @bar
# undefines an existing variable
$x = 5;
undef $x;
print "x = $x\n" if defined $x; # does not print

wantarray

[编辑 | 编辑源代码]
# returns 'true', 'false', or undef if function that called it was called in list, scalar, or void context, respectively.
sub fctn {
   my @vals = (5..10);
   if (wantarray) {
      return @vals;
   } elsif (defined wantarray) {
      return $vals[0];
   } else {
      warn "Warning!  fctn() called in void context!\n";
   }
}
# clones the current process, returning 0 if clone, and the process id of the clone if the parent
my $pid = fork();
if ($pid == 0) {
  print "I am a copy of the original\n";
} elsif ($pid == -1)  {
  print "I can't create a clone for some reason!\n";
} else {
  print "I am the original, my clone has a process id of $pid\n";
}

getpriority

[编辑 | 编辑源代码]

qx/STRING/

[编辑 | 编辑源代码]

setpriority

[编辑 | 编辑源代码]

类和对象

[编辑 | 编辑源代码]

参见 Perl 对象

套接字

[编辑 | 编辑源代码]

getpeername

[编辑 | 编辑源代码]

getsockname

[编辑 | 编辑源代码]

getsockopt

[编辑 | 编辑源代码]

setsockopt

[编辑 | 编辑源代码]

socketpair

[编辑 | 编辑源代码]

登录信息

[编辑 | 编辑源代码]

endhostent

[编辑 | 编辑源代码]

endnetent

[编辑 | 编辑源代码]

网络信息

[编辑 | 编辑源代码]

endprotoent

[编辑 | 编辑源代码]

endservent

[编辑 | 编辑源代码]

gethostbyaddr

[编辑 | 编辑源代码]

bynamegethostent

[编辑 | 编辑源代码]

getnetbyaddr

[编辑 | 编辑源代码]

getnetbyname

[编辑 | 编辑源代码]

getnetent

[编辑 | 编辑源代码]

getprotobyname

[编辑 | 编辑源代码]

getprotoent

[编辑 | 编辑源代码]

getservbyname

[编辑 | 编辑源代码]

getservbyport

[编辑 | 编辑源代码]

getservent

[编辑 | 编辑源代码]

sethostent

[编辑 | 编辑源代码]

setnetent

[编辑 | 编辑源代码]

setprotoent

[编辑 | 编辑源代码]

setservent

[编辑 | 编辑源代码]

时间和日期

[编辑 | 编辑源代码]

将时间戳转换为GMT。

@TimeParts = gmtime();
@TimeParts = gmtime($Time);
$Seconds    = $TimeParts[0]; # 0-59
$Minutes    = $TimeParts[1]; # 0-59
$Hours      = $TimeParts[2]; # 0-23
$DayOfMonth = $TimeParts[3]; # 1-31
$Month      = $TimeParts[4]; # 0-11
$Year       = $TimeParts[5]; # Years since 1900
$DayOfWeek  = $TimeParts[6]; # 0:Sun 1:Mon 2:Tue 3:Wed 4:Thu 5:Fri 6:Sat
$DayOfYear  = $TimeParts[7]; # 1-366

localtime

[编辑 | 编辑源代码]

将时间戳转换为本地时间。

@TimeParts = localtime();
@TimeParts = localtime($Time);
$Seconds    = $TimeParts[0]; # 0-59
$Minutes    = $TimeParts[1]; # 0-59
$Hours      = $TimeParts[2]; # 0-23
$DayOfMonth = $TimeParts[3]; # 1-31
$Month      = $TimeParts[4]; # 0-11
$Year       = $TimeParts[5]; # Years since 1900
$DayOfWeek  = $TimeParts[6]; # 0:Sun 1:Mon 2:Tue 3:Wed 4:Thu 5:Fri 6:Sat
$DayOfYear  = $TimeParts[7]; # 1-366
$Time = time();

返回自纪元(系统相关的,但可能是1970-01-01)以来的秒数。

另见 Time::Hires

@CPUTimes = times();
$UserTimeForProcess    = $CPUTimes[0];
$SystemTimeForProcess  = $CPUTimes[1];
$UserTimeForChildren   = $CPUTimes[2];
$SystemTimeForChildren = $CPUTimes[3];

互相反转的函数

[编辑 | 编辑源代码]

Perl 中的一些函数互相反转或抵消彼此的效果,因此对字符串运行这两个函数都会产生与输入相同的输出,例如

print ord(chr(1));

1 回显到标准输出,

ord() 将字符转换为字符集中的数字,而chr() 将数字转换为相应的字符,因此

就像数学中(假设 x 非负),在 Perl 中ord(chr(1)) = 1chr(ord(1)) = 1

互相反转的函数列表


上一个: 概念索引 索引 下一个: 关键字
华夏公益教科书