in reply to Retain global value across files
If your code was constructed using modules and packages instead of just "files", you could do it like this:
# File My_B.pm package My_B; use strict; use warnings; use base 'Exporter'; our @EXPORT_OK = qw/ verify count_adj count_bfd tc_count /; our $COUNT_ADJ = 0; our $COUNT_BFD = 0; our $TC_COUNT = 1; sub verify { my $fh = shift; my ( $routes, $inet0_total, $inet0_active, $inet6_total, ) = ( 375000, 3436701, 498151, 115803, ); my $pass_count = 1; ... $TC_COUNT++; ... } sub count_adj { $COUNT_ADJ } sub count_bfd { $COUNT_BFD } sub tc_count { $TC_COUNT } 1; # File A (Let's assume this is package main). use strict; use warnings; use FindBin; use lib "$FindBin::Bin"; # For now we'll just assume My_B # is in the same path as File A. use My_B qw/ verify tc_count /; ... verify($fh, 'host', 'state', 'testname'); print tc_count(), "\n";
This strategy is the Perl way; perlmod, although it would be even more Perlish if file My_B.pm lived in myproj/lib/, and file A lived in myproj/bin/.
I used accessor subs so that the user code (File A) isn't tinkering with the package global variables in My_B. If you really wanted access to the variables themselves you can export the symbols, or you can refer to them with their fully qualified names. For example, $My_B::TC_COUNT. But there are other strategies that could also be useful. You could convert this to an OO approach, for example.
Update: Here's an OO version that uses Moose. The benefit to an OO approach is that the counters can be unique to their encapsulating objects.
#!/usr/bin/env perl # File My_B.pm package My_B; use strict; use warnings; use Moose; use namespace::autoclean; my @attributes = qw/ count_adj count_bfd tc_count /; foreach my $attribute ( @attributes ) { has $attribute => ( traits => ['Counter'], is => 'ro', isa => 'Int', default => 0, handles => { "_inc_$attribute" => 'inc' }, ); } sub verify { my( $self, $fh ) = @_; my ( $routes, $inet0_total, $inet0_active, $inet6_total, ) = ( 375000, 3436701, 498151, 115803, ); my $pass_count = 1; #... $self->_inc_tc_count; #... } __PACKAGE__->meta->make_immutable; 1; # File A (Let's assume this is package main). use strict; use warnings; use FindBin; use lib "$FindBin::Bin"; # For now we'll just assume My_B # is in the same path as File A. use My_B; my $fh; # ... my $myb = My_B->new; $myb->verify($fh, 'host', 'state', 'testname'); $myb->verify($fh, 'host', 'state', 'testname'); print $myb->tc_count, "\n";
Dave
|
|---|