hi,

I was exercising package creation and its usage in Perl. I started with a simple program,
1. Created a package called A
2. Created a package called B
3. A program which includes those packages, and uses its services.

# A.pm
package A;
use warnings;

my $l_var = 10;		# lexically scoped variable
$g_var = 20;			# global variable

sub print_arg{
	my $v = shift;
	print "\nyou passed: $v\n";
}

sub sum{
	my ($var1, $var2) = @_;
	@cal = caller;
	print "\nfunc2: im called by, $cal[0]::$cal[1] at $cal[2]";
	
	return $var1+$var2;
}
	
#$res = func2(1,1);
	
1;
# B.pm
package B;
use warnings;

$b = 'package  B';

sub fib{
	my $range = shift;
	($a, $b) = (0, 1);
	while($b<$range){
		print "$b ";
		($a, $b) = ($b, $b+$a);
	}
}

#fib(30);

1;
# demo_package_test.pl
use A;
use B;

A::print_arg('this is an arg.');
my $res = A::sum(10, $A::g_var);
print "\nres = $res";

print "\n---\nb = $B::b";
&B::fib(50);

Output:

you passed: this is an arg.

func2: im called by, main::test_package.pl at 7
res = 30
---
b = Undefined subroutine &B::fib called at test_package.pl line 11.

I dont understand, why im not able to call a function which is defined in the module or Why does Perl says 'Undefined subroutine'.

thanks,
katharnakh.

hmmm...not sure what the problem is, your code works fine for me. Are you sure the B.pm file you posted is the file your main script is accessing?

Where is your B.pm? B isn't a great name for a package - it will clash with the standard 'B' module that ships with Perl. Maybe perl picks up the core B module rather than yours.

I'd recommend a different name.

Good point Bob but it's interesting to note it does work for me as-is. ActiveState Perl 5.8.8 which does include perls 'B' module.

Hey Bob, Kevin big thanks guys...

I was not aware of B module, which ships with perl distribution. Now i have changed the package name and works fine, and its usage in the other script. Well thats a good point Bob.

@Kevin, I am not using Active perl, im using standard distribution of Perl which my employer providing. Well even i dont know how did it worked for you.

well, thanks again.
cheers,
katharnakh.

I'd guess that katharnakh's @INC meant that the core B was 'use'd before the test version.

Yes, I guess. I put the A and B modules in the same directory as the script, not sure if the directory the script is in is found first by @INC or if there is in fact any standard order for @INC at all.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.