inlining a method return

Peter Scott Peter at PSDT.com
Wed Nov 20 20:15:21 CST 2002


>At least, I think inlining is the appropriate term.

No, "lvalue" is what you mean.

>Here's the situation.  I have a sequence object which has a get/set 
>method for
>most of its properties.  For example:
>
>sub seq {
>         my $caller = shift;
>         die "No object.\n" unless ref $caller;
>         @_ ? $caller->{SEQUENCE} = $_[0] : $caller->{SEQUENCE};
>}
>
>This allows something like
>
>print "This is the sequence: ",$obj->seq,"\n";
>
>Moreover, $obj->seq can be inlined with something like length, as in my len
>method:
>
>sub len {
>         my $caller = shift;
>         die "No object.\n" unless ref $caller;
>         $caller->bare;
>         length( $caller->seq );
>}
>
>Finally, I can use msy/// on the sequence key directly, as in:
>
>sub bare {
>         my $caller = shift;
>         die "No object.\n" unless ref $caller;
>         $caller->{SEQUENCE} =~ s/[^rndeqhilkmfpswyvacgtux*-]//gi;
>}
>
>However, I cannot say something like this:
>
>sub residues {
>         my $caller = shift;
>         die "No object.\n" unless ref $caller;
>         my %args = ( GC => '', @_ );
>         $caller->bare;
>         $caller->uppercase;
>         my $p = $caller->profile;
>         #begin problem line
>         $p->{$1}++ while $caller->seq =~ m/([ARNDCQEGHILKMFPSTWYVU])/g;
>         #end problem line
>         if ( $args{GC} ) {
>                 die "%GC on a protein.\n"
>                 unless ( $caller->is_dna || $caller->is_rna );
>                 no warnings;
>                 my $gc = ( $p->{G} + $p->{C} ) / $caller->len * 100;
>         }
>}
>
>How would I inline a get/set method so that I could use it in a msy///
>statement directly rather than first setting a $tmp variable and using the
>$tmp (which is my current workaround)?

You could make an lvaluable method:

% cat foo
#!/bin/perl -l
use strict;
use warnings;

use lib qw(/tmp);
use Foo;
my $obj = Foo->new;
$obj->seq += 42;
print $obj->seq;
$obj->seq =~ s/4/17/;
print $obj->seq;

% cat Foo.pm
package Foo;
use strict;
use warnings;

sub new { bless { }, shift }

sub seq :lvalue {
   my $self = shift;
   $self->{SEQUENCE};
}

1;

% ./foo
42
172


I haven't done this before now, but it seems ok.  As to 
maintainability, that's for you to decide.

perldoc perlsub for more info.
--
Peter Scott
Pacific Systems Design Technologies
http://www.perldebugged.com/




More information about the Victoria-pm mailing list