Home: Perl Programming Help: Advanced:
Identify the modules used in our program



DivyaG
Novice

Nov 5, 2009, 2:01 AM


Views: 5182
Identify the modules used in our program

Hi,
I want to print the module names that are being used by my perl program.
I want to print it in the middle of the program.
@INC contains only the path of the modules but not the names.
Please help me out in this.


shawnhcorey
Enthusiast


Nov 5, 2009, 5:56 AM


Views: 5177
Re: [DivyaG] Identify the modules used in our program

%INC contains the modules and their paths.

Code
#!/usr/bin/perl 

use strict;
use warnings;

use Data::Dumper;

# Make Data::Dumper pretty
$Data::Dumper::Sortkeys = 1;
$Data::Dumper::Indent = 1;

# Set maximum depth for Data::Dumper, zero means unlimited
$Data::Dumper::Maxdepth = 0;

use File::Find;

for my $k ( sort keys %INC ){
printf "%30s %s\n", $k, $INC{$k};
}


__END__

I love Perl; it's the only language where you can bless your thingy.

Perl documentation is available at perldoc.perl.org. The list of standard modules and pragmatics is available in perlmodlib.

Get Markup Help. Please note the markup tag of "code".


DivyaG
Novice

Nov 5, 2009, 9:26 PM


Views: 5155
Re: [shawnhcorey] Identify the modules used in our program

Thanks Shawn,
But the above code will give all the modules present in %INC.
I need only those module names that are used by my program itself.


bichonfrise74
Novice

Nov 8, 2009, 9:55 PM


Views: 5137
Re: [DivyaG] Identify the modules used in our program

I'm not sure why you actually want to do this. But this should help you get started.


Code
#!/usr/bin/perl 

use warnings;
use strict;
use Data::Dumper;

my $file = 'my_script.pl';

open( my $script, '<', $file )
or die "Cannot open $0";

print "Modules used in the program:\n\n";
while (<$script>) {
my ($module) = /^use\s(.*)\;/i;
print "$module\n" if ( $module );
}

close( $script );



--bichonfrise74


DivyaG
Novice

Nov 9, 2009, 4:25 AM


Views: 5127
Re: [bichonfrise74] Identify the modules used in our program

Thanks a lot, but this code will read the input from another file (my_script.pl).
Is there any way to print the module names used by our own script itself.
Eg, script name is test.pl and it is using certain modules, now we want to print the module names in between test.pl code.

This ques was actually being asked in one of the interview, where I got stuck.
So eager to know the solution.


FishMonger
Veteran / Moderator

Nov 9, 2009, 4:32 AM


Views: 5125
Re: [DivyaG] Identify the modules used in our program

The only valid reason I can think of for doing this is that it's a homework assignment.

What have you tried?


bichonfrise74
Novice

Nov 9, 2009, 9:55 AM


Views: 5114
Re: [DivyaG] Identify the modules used in our program

The answer to your question is obvious. And I agree with FishMonger that this sounds like a homework.


--bichonfrise74