Perl tie 函式



描述

此函式將變數 VARIABLE 繫結到提供變數型別實現的包類 CLASSNAME。LIST 中的任何其他引數都將傳遞給整個類的建構函式。通常用於將雜湊變數繫結到 DBM 資料庫。

語法

以下是此函式的簡單語法:

tie VARIABLE, CLASSNAME, LIST

返回值

此函式返回繫結物件的引用。

示例

以下是顯示其基本用法的示例程式碼,我們在 /tmp 目錄中只有兩個檔案:

#!/usr/bin/perl -w

package MyArray;

sub TIEARRAY {
   print "TYING\n";
   bless [];
}

sub DESTROY {
   print "DESTROYING\n";
}

sub STORE {
   my ($self, $index, $value ) = @_;
   print "STORING $value at index $index\n";
   $self[$index] = $value;
}

sub FETCH {
   my ($self, $index ) = @_;
   print "FETCHING the value at index $index\n";
   return $self[$index];
}

package main;
$object = tie @x, MyArray; #@x is now a MyArray array;

print "object is a ", ref($object), "\n";

$x[0] = 'This is test'; #this will call STORE();
print $x[0], "\n";      #this will call FETCH();
print $object->FETCH(0), "\n";
untie @x    		#now @x is a normal array again.

執行以上程式碼後,會產生以下結果:

TYING
object is a MyArray
STORING This is test at index 0
FETCHING the value at index 0
This is test
FETCHING the value at index 0
This is test
DESTROYING

當呼叫 tie 函式時,實際上發生的是呼叫 FileOwner 中的 TIESCALAR 方法,並將 '.bash_profile' 作為引數傳遞給該方法。這將返回一個物件,該物件由 tie 與 $profile 變數關聯。

當在 print 語句中使用 $profile 時,將呼叫 FETCH 方法。當您為 $profile 賦值時,將呼叫 STORE 方法,並將 'mcslp' 作為引數傳遞給該方法。如果您能理解這一點,那麼您可以建立繫結的標量、陣列和雜湊,因為它們都遵循相同的基本模型。現在讓我們檢查一下我們新的 FileOwner 類的詳細資訊,從 TIESCALAR 方法開始:

perl_function_references.htm
廣告

© . All rights reserved.