Update: see post Re^3: Perl Script own path with some more test data between Linux and Windows. Jim spurred some more testing and I now think that Cwd::abs_path($0) is the way to go to get full path name with the caveat that you cannot do any chdir() function before calling this.

In Perl, the automatic variable $0 in some operating systems gives the full path of the currently executing Perl script. In others you just get the name of the file that is executing. The module Cwd will give you the "current working directory". Just see attached code... executed on a Windows 32 bit XP system and a 64 bit Linux system. The combination of basename() and cwd() will always work on all OS'es.

#!/usr/bin/perl -w use strict; use File::Basename; use Cwd; print "dollar 0 is $0\n"; print basename($0), "\n"; print "current working directory is: ",cwd(),"\n"; __END__ On Windows, you get: dollar 0 is C:\TEMP\exename.pl exename.pl current working directory is: C:/TEMP On Linux, you get: dollar 0 is ./exename.pl exename.pl current working directory is: /home/xxx/yy
Moral of the story:
-basename($0) gives the name of the Perl script that is running.
-cwd() gives the current path
-concatenate the result of cwd() and basename($0) with intervening "/" to get the full path of the script in a OS independent way.

Update: Note the Windows cwd() results in "C:/TEMP"! Windows allows the use of the forward-slash ('/') in almost all situations. There is a situation where that is not true (the backslash '\' is required), but I can't remember at the moment what that is. Some Monk will probably enlighten us. My main point is that '/' almost always works to join paths on Windows.


In reply to Re: Perl Script own path by Marshall
in thread Perl Script own path by muzammil18

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.