tags:

views:

127

answers:

2

I want something like..

all_objects.pl

my $sub = $ARGV[1];
...

@objs = get_all_objects();
for my $obj (@objs) {
    // invoke subroutine $sub with param as $obj.   
}

now if I say

all_objects.pl "print 'x '" 

all_objects.pl "print '$_ '"

I should get

obj1 obj2 obj3 ...

i.e. the command line arg act as a subroutine in some way. Can this be achieved?

+1  A: 

Eval is evil unless you really know what you're doing (think of it as an unshielded thermonuclear nuke -- sure you could handle one if you had to, and it might even save the world, but you'd be better off leaving it as a last resort, and let the nuclear physicists deal with it.)

You could put your all_objects.pl code into a module, and then use the module on the command line:

put this into AllObjects.pm:

package AllObjects;
use strict;
use warnings;

sub get_all_objects
{
    # code here...
}
1;

Now on the command line:

perl -I. -MAllObjects -wle'for my $obj (AllObjects::get_all_objects()) { print "object is $obj" }'

However, it's not really clear what you are trying to achieve with the overall design.

You can read more about perl command-line invokation at perldoc perlrun, and making modules at perldoc perlmod (as well as many posts here on Stack Overflow).

Ether
HI Ether, the intention is to avoid repeating some debugging code for self-use, nothing production quality certainly.
baskin
"Debugging code" has a bad habit to stay in production.
codeholic
what repeat of debugging code are you really avoiding with this technique?
ericslaw
*String* `eval` may be an unshielded nuke, but *block* `eval` is just Perl's way of spelling `try`. Not all `eval`s are evil. (But OP was looking for string `eval`, so carry on...)
Dave Sherohman
+4  A: 

eval "" is bad. Use something like the following, if it fulfills your needs:

my ($sub) = @ARGV;

my %prepared = (
    print => sub { print "$_[0]\n" },
    woof  => sub { $_[0]->woof },
    meow  => sub { $_[0]->meow },
);

@objs = get_all_objects();
for my $obj (@objs) {
    $prepared{$sub}->($obj);   
}

Update: For debugging purposes, Perl has a debugger: perldoc perldebug

codeholic