Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display the number of subroutines and their names in a perl script at the time of its execution?

Tags:

regex

linux

perl

Consider the following Perl script script.pl as an example:

use strict;
use warnings;
sub f1
{statements}
sub f2
{statements}
sub f3
{statements}
f1();f2();f3();

When I execute the script, it should show the following output:

./script.pl

number of subroutines:3
names of subroutines:f1 f2 f3

When the code is executed, how can I count the number of subroutines, get their names, and then print them during runtime?

like image 521
Vamsee Bond Avatar asked Nov 22 '25 09:11

Vamsee Bond


1 Answers

You are looking for Devel::Symdump:

#!/usr/bin/env perl

use strict;
use warnings;

{
    require Devel::Symdump;
    my $sym = Devel::Symdump->new('main');
    my @subs = $sym->functions;
    printf "Number of subroutines: %d\n", scalar @subs;
    printf "Names of subroutines: %s\n", join(q{, } => map { s/^main:://; $_ } @subs);
}

sub f1 {
    # statements
}

sub f2 {
    # statements
}

sub f3 {
    # statements
}

f1();
f2();
f3();

Output:

Number of subroutines: 3
Names of subroutines: f2, f1, f3
like image 195
Sinan Ünür Avatar answered Nov 23 '25 23:11

Sinan Ünür