开发者

How to keep a variable in scope to all subroutines

开发者 https://www.devze.com 2023-01-23 07:57 出处:网络
i am trying to create a module which is like this package MyModule;开发者_Go百科 use strict; use Exporter;

i am trying to create a module which is like this

package MyModule;开发者_Go百科

use strict;
use Exporter;
use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);

$VERSION = 1.00;
@ISA = qw(Exporter);
@EXPORT = qw(func1);

sub func1 {    
    my x = shift;    
    print x;    
    func2();    
}

sub func2 {    
    print x;    
}

and from a perl script, i am calling func1 of the module and passing a variable x. how do i make that variable visible to both subroutines or say all the functions inside that module. Please help.


Declare $x in the scope of the file using my or our:

my $x;

# subroutines definition

File has the largest lexical scope, so the variable will be visible for the rest of code (unless you re-declare it in some inner scope using my).


Make $x lexical to the package file rather than a single subroutine:

package MyModule;

use strict;
use Exporter;
use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);

$VERSION = 1.00;
@ISA = qw(Exporter);
@EXPORT = qw(func1);

my $x;

sub func1 {

    $x = shift;
    print $x;

    func2();
}

sub func2 {

    print $x;
}

But this example doesn't really make sense. A more sensible example would be to define a lexical filehandle that multiple subroutines within the package print to:

package PoorManLogger;

my $fileHandle;

sub initialize { open $fileHandle, '<', +shift }

sub alert { print $fileHandle 'ALERT: ', @_, "\n"; }

sub debug { print $fileHandle 'DEBUG: ', @_, "\n"; }

sub close { close $fileHandle; }  # Though this isn't technically needed.

1;


One of the main benefits of OO is encapsulation:

#!/usr/bin/perl

package MyModule;

use strict; use warnings;

sub new {
    my $class = shift;
    bless { x => shift } => $class;
}

sub x {
    my $self = shift;
    $self->{x} = shift if @_;
    return $self->{x};
}

sub func2 {
    my $self = shift;
    print $self->x, "\n";
}

package main;

use strict; use warnings;

my $m = MyModule->new(5);

$m->func2;

$m->x(7);

$m->func2;


see our

(comments to my suggestion are correct, my suggestion wasn't)

0

精彩评论

暂无评论...
验证码 换一张
取 消