Perl 中的 tie函数

首页 / Perl入门教程 / Perl 中的 tie函数

描述

此函数将VARIABLE与提供了变量类型实现的包类CLASSNAME关联。 LIST中的所有其他参数都将传递给整个类的构造函数。通常用于将哈希变量绑定到DBM数据库。

语法

以下是此函数的简单语法-

tie VARIABLE, CLASSNAME, LIST

返回值

此函数返回对绑定对象的引用。

以下是显示其基本用法的示例代码,/tmp目录中只有两个文件-

链接:https://www.learnfk.comhttps://www.learnfk.com/perl/perl-tie.html

来源:LearnFk无涯教程网

#!/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"作为该方法的参数传递。这将返回一个对象,该对象通过绑定到$profile变量来关联。

当在打印语句中使用$profile时,将调用FETCH方法。当您为$profile分配值时,将调用STORE方法,并以'mcslp'作为该方法的参数。如果可以遵循,则可以创建绑定标量,数组和哈希,因为它们都遵循相同的基本模型。现在让我们从TIESCALAR方法开始检查新FileOwner类的详细信息-

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

Android开发高手课 -〔张绍文〕

大规模数据处理实战 -〔蔡元楠〕

NLP实战高手课 -〔王然〕

视觉笔记入门课 -〔高伟〕

Linux内核技术实战课 -〔邵亚方〕

手机摄影 -〔@随你们去〕

全链路压测实战30讲 -〔高楼〕

自动化测试高手课 -〔柳胜〕

PPT设计进阶 · 从基础操作到高级创意 -〔李金宝(Bobbie)〕

好记忆不如烂笔头。留下您的足迹吧 :)