Perl 程式設計/函式參考
僅當最後一個字元被識別為記錄分隔符(例如換行符)時,才從字串中刪除最後一個字元。
?
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
將數字轉換為八進位制。
ord
[edit | edit source]將字元轉換為數字。
print ord("A"); # prints 65
pack
[edit | edit source]接受一個列表,並使用提供的規則集將其轉換為字串。
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.
每個字母可以選擇後跟一個數字,表示重複次數。
整數型別 s、S、l 和 L 可以直接後跟 ! 字尾,表示本地短整數或長整數。
reverse
[edit | edit source]反轉字串(在標量上下文中)或列表(在列表上下文中)。
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"
rindex
[edit | edit source]在一個字串中查詢另一個字串,從字串末尾開始搜尋。
$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)
sprintf
[edit | edit source]列印格式化的字串。
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
[edit | edit source]返回字串的一部分(一個子字串)。
格式:substr 字串 起始位置 長度
- 起始位置 是從零開始的。
- 負數表示從字串末尾開始。
$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'
uc
[edit | edit source]$Uppercase = uc($String);
將字串轉換為大寫。
ucfirst
[edit | edit source]將字串的第一個字元轉換為大寫。
數值函式
[edit | edit source]abs
[edit | edit source]返回一個數字的絕對值(正值)。
$Number = abs(-100); # Returns 100;
atan2
[edit | edit source]# Converts cartesian(x,y) coordinates into an angle $Number = atan2($Y, $X);
cos
[edit | edit source]# Returns the cosine of an angle (radians) $Number = cos($Angle); # Cosine = Adjacent/Hypotenuse
exp
[edit | edit source]# Raises e to a specified power
$Number = exp(2); # Returns e^2
e ≈ 2.71828183 more about e
hex
[edit | edit source]# Interprets a string as hexidecimal, and returns its value
$Number = hex("10"); # Returns 16
$Number = hex("0xFF"); # Returns 255
int
[edit | edit source]將一個數字向零方向取整,返回一個整數。
$Number = int(-1.6); # Returns -1 $Number = int(0.9); # Returns 0 $Number = int(28.54); # Returns 28
log
[edit | edit source]# 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
oct
[edit | edit source]# Interprets a string as octal, and returns its value
$Number = oct("10"); # Returns 8
$Number = oct("21"); # Returns 17
rand
[edit | edit source]# 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
sin
[edit | edit source]# Returns the sine of an angle (radians) $Number = sin($Angle); # Sine = Opposite/Hypotenuse
sqrt
[edit | edit source]# 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 模組。
srand
[edit | edit source]# Seeds (sets-up) the random-number generator srand();
與版本相關,並且不能保證舊版本的 Perl 具有良好的種子值。有關更多可能性,請參閱 Math::TrulyRandom 模組。當前版本的 Perl 使用 urandom 裝置(如果可用)。
陣列函式
[edit | edit source]pop
[edit | edit source]$LastElement = pop(@MyArray);
從陣列中獲取最後一個元素。
push
[edit | edit source]push(@MyArray, "Last element"); push(@MyArray, "several", "more", "elements");
將列表中的元素壓入陣列末尾。
shift
[edit | edit source]shift(@MyArray); # Delete the first element $FirstElement = shift(@MyArray); # Delete the first element, load it into $FirstElement instead
從陣列中取出第一個元素。
splice
[edit | edit source]# 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
[edit | edit source]unshift(@MyArray, "New element"); unshift(@MyArray, "several", "more", "elements");
將列表中的元素新增到陣列開頭。
列表函式
[edit | edit source]grep
[edit | edit source]# 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);
join
[edit | edit source]# Joins the items of a list into a single string $OneItemPerLine = join( "\n", @List); $EverythingBunchedTogether = join( "", @List); $Filename = join( "/", ($Directory, $Subdirectory, $Filename));
map
[edit | edit source]# 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 未開啟,則此函式返回 true。FILEHANDLE 可以是表示式,其值為真正的檔案控制代碼,也可以是某種檔案控制代碼物件的引用。沒有引數的 eof 返回上次讀取檔案的末尾檔案狀態。帶有空括號 () 的 eof() 測試 ARGV 檔案控制代碼(最常見的是在 <> 中作為空檔案控制代碼)。因此,在 while (<>) 迴圈內部,帶有括號的 eof() 只能檢測到一組檔案中最後一個檔案的末尾。在 while (<>) 迴圈中使用 eof(不帶括號)來測試每個檔案。例如,以下程式碼在最後一個檔案的最後一行之前插入連字元
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
列印給定的引數。
在以下部分中討論
請參見頁面上方的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 身份執行才能成功。
# 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);
caller
# !/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”函式。相反,在編寫模組時,約定俗成地建立一個名為“import”的子程式,它使用該模組需要的變數或方法填充當前名稱空間。
如果您的類將“Exporter”模組作為基類,則標準的“Exporter”模組提供了 import 方法。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
require
require Foo::Bar; # identical to: require 'Foo/Bar.pm';
use
use Foo qw/bar baz/;
BEGIN {
require Foo;
import Foo qw/bar baz/;
}
在編譯時需要並匯入給定的模組或pragma。該行
等同於# 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
# 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";
}
另見 Perl 物件
將時間戳轉換為格林尼治標準時間。
@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
將時間戳轉換為本地時間。
@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 非負),ord(chr(1)) = 1 和 chr(ord(1)) = 1 在 Perl 中。
互相反轉的函式列表