in reply to Re^3: At which line number did the print statement occure?
in thread At which line number did the print statement occure?

$0 and __FILE__ are subtly different. $0 will only ever contain the name of the program that is running. If the program calls code in other files (modules, for example) then __FILE__ will have different values.

These values are documented in the section on "Special Literals" in perldata.

--
<http://dave.org.uk>

"The first rule of Perl club is you do not talk about Perl club."
-- Chip Salzenberg

  • Comment on Re^4: At which line number did the print statement occure?

Replies are listed 'Best First'.
Re^5: At which line number did the print statement occure?
by Sartak (Hermit) on Oct 13, 2006 at 17:32 UTC

    The distinction between $0 and __FILE__ is handy. You can use it to implement unit tests for classes. I do this a lot in Ruby. For example, in classFoo.pm:

    #/usr/bin/perl package Foo; sub new { # ... } # other stuff if (__FILE__ eq $0) { my $foo = new Foo; # test foo's methods, etc } 1;

    Now you'll only get the unit tests if you run classFoo.pm directly, because otherwise, __FILE__ ne $0.

    Of course, I must recommend using Test::More and friends instead. Just showing a possible application of the subtle difference between __FILE__ and $0.

      caller is more reliable for this.
      #!/usr/bin/perl package Foo; sub new { # ... } # other stuff if (!caller()) { my $foo = new Foo; # test foo's methods, etc } 1;