问题
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?
input file(from linux command 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%
My subroutine:
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 $_;
}
My query:
How can i pass my subroutine as hash into another subroutine?
example: g_usrs_data() -> this is my subroutine .
the above subroutine should be passed into another subroutine (i.e into usrs_hash as hash table)
example: create_db(usrs_hash,$sql1m)
回答1:
Subroutines can be passed around as code references. See perlreftut and perlsub.
An example with an anonymous subroutine
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";
This silly program prints
In coderef. Got: |arguments to pass| 7
Notes on code references
The anonymous subroutine is assigned to a scalar
$rc
, making that a code referenceWith an existing (named) sub, say
func
, a code reference is made bymy $rc = \&func;
This
$rc
is a normal scalar variable, that can be passed to subroutines like any otherThe 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
As anonymous assign by
= sub { }
, much like= [ ]
(arrayref) and= { }
(hashref)For a named sub use
&
instead of a sigil, so\&
for sub vs.\@
(array) and\%
(hash)They are used by
->()
, much like->[]
(arrayref) and->{}
(hashref)
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.
For far more see this article from Mastering Perl and this article from The Effective Perler.
来源:https://stackoverflow.com/questions/41457255/how-to-pass-entire-subroutine-into-hashtable-data-using-perl