On Jul 15, Connie Chan said:

>### Lib 1 ###
>use strict;
>our %abc;
>$abc{a} = 1;
>$abc{b} = 2;
>### EOF Lib 1 ###
>
>### Lib 2 ###
>use strict;
>our $a = "ME";
>### EOF Lib 2 ###

You've made the mistake of using $a (or $b) as a variable name.  These two
variables are protected from use strict 'vars', because they are used in
sorting routines:

  my @sorted = sort { $a <=> $b } @numbers;

>### Script 1 ###
>use strict;
>eval { require "lib1.pl" } or die "lib 1";
>eval { require "lib2.pl" } or die "lib 2";
>
>print $abc{a};
>### EOF Script 1 ###
>
>When I run script 1, Perl throws me the err of 'explicit package',
>but if I change to print $a, instead of $abc{a}, I got  "ME" correctly...
>Why ?

The our() declaration ONLY HAS EFFECT in the scope it is declared in.
That means it won't affect another file.  And even MORE importantly,
require() happens AT RUN-TIME, and use strict 'vars' is a COMPILE-TIME
check.  That means that even if you had put

  use vars '%abc';

in the libraries, you wouldn't have been ok, because the libraries you
wrote get require()d.  You could get around that with a BEGIN block, which
forces compile-time execution.

  # foo.pl
  use strict;
  use vars '$x';
  $x = 10;

  # main.pl
  use strict;
  BEGIN { require "foo.pl" }
  print $x;  # no error :)

>Besides, how can I make some hash just like %ENV, so can access
>everywhere ?

You can create a variable (scalar, array, hash, even function!) that is
available in ALL packages by using a special caret-syntax:

  package foo;
  use strict;
  ${^name} = 1;  # no error!

  package bar;
  use strict;
  print ${^name};  # 1, no error!

-- 
Jeff "japhy" Pinyan      [EMAIL PROTECTED]      http://www.pobox.com/~japhy/
RPI Acacia brother #734   http://www.perlmonks.org/   http://www.cpan.org/
** Look for "Regular Expressions in Perl" published by Manning, in 2002 **
<stu> what does y/// stand for?  <tenderpuss> why, yansliterate of course.
[  I'm looking for programming work.  If you like my work, let me know.  ]


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to