[BioPython] Perl Question

Danny Yoo dyoo@acoma.Stanford.EDU
Mon, 6 Jan 2003 12:14:58 -0800 (PST)


On Mon, 6 Jan 2003, shahzeb niazi wrote:


> I want to pass a math operator to a subroutine. The subroutine is
> supposed to search for certain values according to a criteria passes,
> e.g ==, <, > ... now, the quick and dirty way to do this would be to
> just have a variable, say $criteria, with numbers and then a bunch of
> if/elsif in the subroutine for each number. However, I'm curious: is
> there a way to use a scalar as an operator? Something like this maybe:
>
> $criteria = "<"; $value1 = "1"; $value2 = "2";
>
> if($value1 $criteria $vaue2){ print "$value1 is smaller than $value2\n";
> }

Hi Shahzeb,

Hmmm... this is a general Perl learning question than a BioPython
question: you may want to ask this on a general Perl mail lists for more
authorative help.  Please post in a more appropriate forum next time.


To answer your question: Yes.  You can pass a "subroutine reference"  ---
a scalar value --- as a parameter to another subroutine.  For example:

###
sub my_less_than {
    my ($a, $b) = @_;
    return $a < $b;
}

sub my_greater_than {
    my ($a, $b) = @_;
    return $a > $b;
}


sub choose_criteria {
    print "Choose criterion: '<' or '>': ";
    my $choice = <>;
    if ($choice =~ m/>/) {
        return \&my_less_than;
    }
    else {
        return \&my_greater_than;
    }
}

my $value1 = 42;
my $value2 = 43;
my $criteria = choose_criteria();
print "What does my criteria say?  ";
print $criteria->($value1, $value2);
###


For more information on this, you can look at the 'perlref' documentation
for Perl.  Look for the word "closure", and you should see some
interesting material there.


Good luck to you!