Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re: alternative way to subs

by Codon (Friar)
on Apr 30, 2008 at 16:55 UTC ( #683725=note: print w/ replies, xml ) Need Help??


in reply to alternative way to subs

Taking the idea behind Corion's code, but working on how to do this without needing to modify the individual scripts, I came up with the idea of wrapping the code of each script into a subroutine in your General.pl. I've banged together a script that works (for some definition), but I'm sure could run afoul if you aren't careful or if your needs are not quite the same as the assumptions I made.

#!/usr/bin/perl use strict; use warnings; my @modules = qw(1 2 3 4); my %sub; for my $module (@modules) { if ( -e "$module.pl" and -r "$module.pl" ) { local $/; open my $fh, '<', "$module.pl" or die "cannot open $module.pl: $ +!\n"; my $perl = <$fh>; close $fh; my $sub = sub { local @ARGV = @_; eval $perl; warn "$module failed: $@\n" if ($@); }; if ($@) { die "$module.pl failed to load: $@\n"; } $sub{$module} = $sub; } else { die "$module.pl does not exist or is not readable\n"; } } for my $sub ( @modules ) { warn "calling $sub\n"; $sub{$sub}->(); } print "finished calling all modules\n";
I happen to have several scripts in my directory (1.pl, 2.pl, 3.pl, etc.) because I use them for writing test / proof of concept code. This works in that it wraps each file in a subroutine; it calls each subroutine; the work is done; output is returned as expected and errors are trapped and handled. This requires no modification to the existing scripts. If you need to pass arguments to the scripts, they can be passed to the subourtines and all is rosey.

Ivan Heffner
Sr. Software Engineer
WhitePages.com, Inc.


Comment on Re: alternative way to subs
Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://683725]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (5)
As of 2014-12-28 14:19 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (181 votes), past polls