1

If someone can think of a more eloquent way of wording my title, please feel free to offer suggestions...I feel as though there is a word for what I'm trying to do, but it's escaping me.

Anyways, I've got a bunch of Perl scripts I've made and each one has a "usage()" method that essentially describes how to use the respective script. Now, I've also got a package that is utilized by each of these scripts (Flags.pm) which parses command line arguments for the script to use. What I want to do is have it so that the method called within Flags.pm (getArguments()) will try to determine if a particular flag is set (e.g. -help), and then from within that method call the parent scripts "usage()" method.

The idea is to avoid having to put the code to call "usage()" within each script, since each script will be calling it under the same conditions. I want my getArguments() in Flags.pm to handle it. Basically, I just want to achieve this...

Flags.pm

package Flags;

sub getArguments() {
   usage();
}

1;

MyScript.pl

use Flags;

sub usage() {
   print "Hello World";
}

$args=Flags->getArguments();

TL;DR: importing a Perl package for a script. want to call a method found in the script from within a method in the imported package.

4

3 に答える 3

3

I would probably opt for passing to getArguments a reference to the sub that prints the usage information:

package Flags;

use strict; use warnings;

sub getArguments {
    my $usage = shift;
    return $usage->(__PACKAGE__);
}

package main;

use strict; use warnings;

sub usage {
    my $pkg = shift;
    return sprintf "%s: Usage information", $pkg;
}

print Flags::getArguments(\&usage), "\n";

Output:

C:\temp> uu
Flags: Usage information
于 2013-02-21T17:04:55.307 に答える
1

From what I understand from your three paragraphs of text, what you want is that your Flags.pm subroutine calls the usage subroutine of the main script, whatever that subroutine may be. Why not do:

sub getArguments() {
   main::usage();
}

main is the top level package, i.e. your main script.

于 2013-02-21T16:38:55.283 に答える
0

正しい方法ではありません。

package Flags;

our $USAGE;

sub set_usage {
   $USAGE = $_[0];
}

sub usage {
   print 'No usage'
      unless defined $USAGE;
   print $USAGE;
}

sub getArguments() {
   usage();
}

1;

および.pl

use Flags;

Flags->set_usage('Usage here');

$args=Flags->getArguments();

サブを使用したい場合

package Flags;

our $USAGE;

sub set_usage {
   $USAGE = $_[0];
}

sub usage {
   print 'No usage'
      unless defined $USAGE;
   &$USAGE;
}

sub getArguments() {
   usage();
}

1;

および.pl

use Flags;

my $usage_sub = sub {
    print 'Hello World!!!';
}

Flags->set_usage($usage_sub);

$args=Flags->getArguments();
于 2013-02-21T16:59:01.007 に答える