跳轉到內容

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

互相反轉的函式列表


上一個: 概念索引 索引 下一個: 關鍵字
華夏公益教科書