zašto $out radi kada je u main scope-u, tj. zašto zapravo nije
$foobar::out?
#!/usr/bin/perl
use warnings;
use strict;
use Data::Dump qw(dump);
my $out; # this works
foobar::run( qw/ foo bar baz foo/ );
warn dump $out;
package foobar;
use warnings;
use strict;
#my $out; # XXX this doesn't work!
sub run {
my $code = eval q|
sub {
my $name = shift;
$out->{$name}++;
}
|;
$code->( $_ ) foreach @_;
}
--
Dobrica Pavlinusic 2share!2flame dpa...@rot13.org
Unix addict. Internet consultant. http://www.rot13.org/~dpavlin
Da odgovorim na svoje pitanje: zato jer perl ima file scope...
Kada to podjelim na dva file-a radi jedino:
--- main.pl ---
#!/usr/bin/perl
use warnings;
use strict;
use Data::Dump qw(dump);
use foobar;
foobar::run( qw/ foo bar baz foo/ );
warn dump $foobar::out;
--- foobar.pm ---
package foobar;
use warnings;
use strict;
my $out; # XXX this doesn't work!
sub run {
my $code = eval q|
sub {
my $name = shift;
$foobar::out->{$name}++;
}
|;
$code->( $_ ) foreach @_;
}
1;
Bezobrazni copy-paste sa http://perldoc.perl.org/functions/my.html:
A my declares the listed variables to be local (lexically) to the
enclosing block, file, or eval.
Viđao sam da ljudi rade ovakve stvari:
package main;
{
my $var; # Vidljivo samo unutar ovog bloka
... kod koji koristi $var...
}
--
IgorR
Damian Conway je to stalno koristio za njegov Class::Std, inace stara
knjiga Object Oriented Perl :)
http://search.cpan.org/~dconway/Class-Std-v0.0.8/lib/Class/Std.pm#Automating_Inside-Out_Classes
Boris.
Ma, da... taj implicitni { scope } je cool i čak ga i sam koristim
(povremeno) ali nekako uvijek zaboravim na taj file scope...
Mala škola Enterprise Perla, lekcija br. 114:
Jedan package, jedan file. I obratno.
;)
--
IgorR