0

I have a perl script and its been executing from "/root/pkt/sw/se/tool" path and would need the complete directory path inside the script.

Can you please let me know how would i get the complete path?

sample.pl

 our ($tool_dir);

 use strict;
 use warnings;
 BEGIN {
   $tool_dir = $0;
   my $home_path = $tool_dir
   $home_path =~ s|\w*/\w*/\w*$||;
   my $target_path ="obj/Linux-i686/usr/share/ddlc/lib";
   $lib_dir = "$home_path$target_path";
   unshift(@INC, $lib_dir);
 }

And i am executing this script from "pkt/sw/se/tool" path but here i am getting only "pkt/sw/se/tool" instead of "/root/pkt/sw/se/tool"

my perl script is available under /root/pkt/sw/se/tools/sample.pl

3 Answers 3

2

You can use the CWD module (http://perldoc.perl.org/Cwd.html) (code take from that page)

use Cwd;
my $dir = getcwd;
use Cwd 'abs_path';
my $abs_path = abs_path($file);

or you could execute the pwd command

$cwd = `pwd`;

If you just want the directory, not the full path, you could check out an existing answer at Print current directory using Perl

Sign up to request clarification or add additional context in comments.

2 Comments

At the line 3 why declare the use Cwd 'abs_path'; repeated? declare abs_path at the line 1 which is working.
@Hussain, see the original answer to which I linked and ask there :-)
1

Use one of the modules already mentioned, never use backticks - unless you fully understand the risks and implications of doing so. If you do want to run 'pwd' then call it via something like IPC::Run3.

Examples:

#!/usr/bin/perl

use strict;
use warnings;

use Cwd;
use IPC::Run3;

# CWD
my $working_dir_cwd = getcwd; 
print "Woring Dir (Cwd): $working_dir_cwd\n";

# IPC::Run3
my ($in, $out, $err);
my @command = qw/pwd/;

run3 \@command, $in, \$out, \$err or die $?;

print "Working Dir (pwd): $out\n";

2 Comments

can you please let me know how do i use 'pwd' via IPC::Run?
Sorry, I meant IPC::Run3. Take a look at the example script (edit). You'll see calling Cwd is a lot less code - but IPC::Run3 is very useful for safely running commands (simple or complex) and capturing the result.
0

You can use FindBin to locate directory of original perl script.

use FindBin;
use lib "$FindBin::Bin/../../../obj/Linux-i686/usr/share/ddlc/lib";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.