1

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?

3
  • 4
    This script will finally shoot your leg off, remember my words. Commented Feb 24, 2010 at 15:44
  • 2
    Why do you want to do this? We might be able to suggest a better way if we know what the point is. Commented Feb 24, 2010 at 22:28
  • baskin wants to do some debugging stuff. See comments to Ether's post. Commented Feb 25, 2010 at 7:53

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

Comments

1

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).

3 Comments

HI Ether, the intention is to avoid repeating some debugging code for self-use, nothing production quality certainly.
what repeat of debugging code are you really avoiding with this technique?
String eval may be an unshielded nuke, but block eval is just Perl's way of spelling try. Not all evals are evil. (But OP was looking for string eval, so carry on...)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.