Beefy Boxes and Bandwidth Generously Provided by pair Networks Russ
P is for Practical
 
PerlMonks  

Difference between $0 and __FILE__

by solegaonkar (Sexton)
on Sep 26, 2012 at 04:05 UTC ( #995692=perlquestion: print w/ replies, xml ) Need Help??
solegaonkar has asked for the wisdom of the Perl Monks concerning the following question:

Hello Monks, Often wondered what is the difference between the two special values $0 and __FILE__ in a Perl script. But always brushed it off saying "Perl has many ways to do anything". But, today, I saw some code containing:
unless ($0 eq __FILE__) .....
That sets me thinking, what exactly is the difference between the two. Can they be different? When?

Comment on Difference between $0 and __FILE__
Download Code
Re: Difference between $0 and __FILE__
by BrowserUk (Pope) on Sep 26, 2012 at 04:28 UTC

    Within a module (say a.pm) used from a program (say b.pl), __FILE__ will be a.pm but $0 will be b.pl.

    The test you posted checks whether the file that contains it is being run as a 'main' program, or is being used or required, or done or eval'd.


    With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.

    RIP Neil Armstrong

Re: Difference between $0 and __FILE__
by pobocks (Chaplain) on Sep 26, 2012 at 04:45 UTC

    __FILE__ is the file name that the __FILE__ token is in, and $0 is a variable containing the name of the program, as given to the shell.

    They can most certainly be different - one case that comes to mind is a __FILE__ token in a library called by your program, but there are many others, particularly since you can assign to $0 (with varying effects on different OS), but you can't meaningfully assign to __FILE__.

    Example code:

    File 1 - firstfile

    #!/usr/bin/perl -w use strict; print $0 . "\n"; print __FILE__ . "\n"; do 'filetwo';

    File 2 - filetwo

    #!/usr/bin/perl -w use strict; print $0 . "\n"; print __FILE__ . "\n";

    It's simplistic, but should show the basic concept.

    for(split(" ","tsuJ rehtonA lreP rekcaH")){print reverse . " "}print "\b.\n";
      That explains it! Thank you!!

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://995692]
Approved by lidden
Front-paged by lidden
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (3)
As of 2014-04-21 00:09 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    April first is:







    Results (489 votes), past polls