How to pass entire routine to hash data using Perl?

I have the following subroutine that I have to pass the subroutine as a hash table, and this hash table should be called again inside another subroutine using perl?

input file (from linux bdata command):

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 routine:

 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 request:

How can I pass my subroutine as a hash to another subroutine?

example: g_usrs_data () -> this is my routine.

the above routine must be passed to another routine (i.e. in usrs_hash as a hash table)

example: create_db (usrs_hash, $ sql1m)

0
source share
1 answer

Subroutines can be referred to as code references. See perlreftut and perlsub .

Anonymous routine example

 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 stupid program prints

  In coderef.  Got: | arguments to pass |
 7

Code Link Notes

  • An anonymous routine is assigned to the scalar $rc , which makes it a reference to the code

  • With an existing (named) subroutine, say func , a link to the code is made by my $rc = \&func;

  • This $rc is a normal scalar variable that can be passed to routines, like any other

  • Then the subroutine is called $rc->(); where in brackets we can pass arguments

Note that the syntax for creating and using them is the same as for other data types.

  • As an anonymous assignment using = sub { } , it is very similar to = [ ] (arrayref) and = { } (hashref)

  • For a named routine, use & instead of sigils, therefore \& for a subordinate against \@ (array) and \% (hash)

  • They are used ->() , very similar to ->[] (arrayref) and ->{} (hashref)

For links in general, see Perlreftut . Subroutines are described in detail in perlsub .


See, for example, this post on anonymous subscriptions with multiple answers.

For more see this article from Mastering Perl and this article from Effective Perler.

+3
source

Source: https://habr.com/ru/post/1262344/


All Articles