问题描述
我有以下子例程,我应该将该例程作为哈希表传递,并且应该使用perl在另一个子例程中再次调用该哈希表?
I have the following subroutine which i should pass the routine as hashtable and that hashtable should be again called inside another subroutine using perl?
输入文件(来自linux命令bdata):
NAME PEND RUN SUSP JLIM JLIMR RATE HAPPY
achandra 0 48 0 2000 50:2000 151217 100%
agutta 1 5 0 100 50:100 16561 83%
我的子例程:
sub g_usrs_data()
{
my($lines) = @_;
my $header_found = 0;
my @headers = ();
my $row_count = 0;
my %table_data = ();
my %row_data = ();
$lines=`bdata`;
#print $lines;
foreach (split("\n",$lines)) {
if (/NAME\s*PEND/) {
$header_found = 1;
@headers =split;
}
elsif (/^\s*$/)
{
$header_found=0;
}
$row_data{$row_count++} = $_;
#print $_;
}
我的查询:
如何将我的子例程作为哈希传递给另一个子例程?
How can i pass my subroutine as hash into another subroutine?
示例:g_usrs_data()->这是我的子程序.
example:g_usrs_data() -> this is my subroutine .
上述子例程应传递到另一个子例程(即作为哈希表传递到usrs_hash中)
the above subroutine should be passed into another subroutine (i.e into usrs_hash as hash table)
示例:create_db(usrs_hash,$ sql1m)
example:create_db(usrs_hash,$sql1m)
推荐答案
子例程可以作为代码引用传递.请参见 perlreftut 和 perlsub .
Subroutines can be passed around as code references. See perlreftut and perlsub.
带有匿名子例程的示例
use warnings;
use strict;
my $rc = sub {
my @args = @_;
print "\tIn coderef. Got: |@_|\n";
return 7;
}; # note the semicolon!
sub use_rc {
my ($coderef, @other_args) = @_;
my $ret = $coderef->('arguments', 'to', 'pass');
return $ret;
}
my $res = use_rc($rc);
print "$res\n";
这个愚蠢的程序打印
In coderef. Got: |arguments to pass|
7
关于代码引用的注意事项
Notes on code references
-
匿名子例程被分配给标量
$rc
,从而使代码引用
对于现有的(命名的)子对象,例如func
,由my $rc = \&func;
With an existing (named) sub, say func
, a code reference is made by my $rc = \&func;
此$rc
是普通的标量变量,可以像其他变量一样传递给子例程
This $rc
is a normal scalar variable, that can be passed to subroutines like any other
该子然后被$rc->();
调用,在括号中,我们可以为其传递参数
The sub is then called by $rc->();
where in parenthesis we can pass it arguments
请注意,创建和使用它们的语法与其他数据类型一样
Note that the syntax for creating and using them are just like for other data types
-
作为
= sub { }
的匿名分配,与= [ ]
(arrayref)和= { }
(hashref)
As anonymous assign by
= sub { }
, much like= [ ]
(arrayref) and= { }
(hashref)
对于命名子对象,请使用&
而不是sigil,因此对于子对象与\@
(数组)和\%
(哈希)
For a named sub use &
instead of a sigil, so \&
for sub vs. \@
(array) and \%
(hash)
它们被->()
使用,非常类似于->[]
(arrayref)和->{}
(hashref)
They are used by ->()
, much like ->[]
(arrayref) and ->{}
(hashref)
有关一般参考,请参见 perlreftut .子例程在 perlsub 中有详细介绍.
For references in general see perlreftut. Subroutines are covered in depth in perlsub.
例如,参见这篇文章在匿名订阅中,并给出了许多答案.
See for example this post on anonymous subs, with a number of answers.
更多信息,请参见中的本文精通Perl 和这篇文章有效佩勒中的a>.
For far more see this article from Mastering Perl and this article from The Effective Perler.
这篇关于如何使用Perl将整个子例程传递到哈希表数据中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!