1

I'm trying to get the inode alone of a file that is passed through as an argument.

When I extract the inode, however, there is a 0 printed on a new line. I've tried to get rid of it with regex but I can't. I'm passing the script /usr/bin/vim The 0 isn't there when I run the command (ls -i /usr/bin/vim | awk '{print $1}'), but it is when I run my script.

How can I get rid of this 0?

my $filepath = $ARGV[0];
chomp $filepath;
$filepath =~ s/\s//g;

print ("FILEPATH: $filepath\n"); #looks good
my $inode = system("ls -i $filepath | awk '{print \$1}'");

$inode =~ s/[^a-zA-Z0-9]//g;
$inode =~ s/\s//g;
print ("$inode\n");

So my result is

137699967
0
ThisSuitIsBlackNot
  • 23,492
  • 9
  • 63
  • 110
D. Smith
  • 19
  • 1
  • 2
    so the question tagged with `vim` just because you `ls -i /usr/bin/vim`? – Kent Apr 01 '16 at 14:00
  • Helpful: http://stackoverflow.com/questions/799968/whats-the-difference-between-perls-backticks-system-and-exec – mob Apr 01 '16 at 14:55

2 Answers2

3

When you invoke system you run the command provided as its argument, and that's what's outputting the inode number.

The return value of system is the exit code of the command run, which in this case is 0, and that's what your subsequent print call outputs.

To run an external program and capture its output, use the qx operator, like so:

my $inode = qx/ls -i $filepath | awk '{print \$1}'"/;

However, as Sobrique explained in their answer, you don't actually need to call an external program, you can use Perl's built-in stat function instead.

my $inode = stat($filepath)[1];

stat returns a list containing a variety of information about a file - index 1 holds its inode. This code won't handle if the file doesn't exist, of course.

Matthew Walton
  • 9,809
  • 3
  • 27
  • 36
2

Don't, just use the stat builtin instead

print (stat($filepath))[1]."\n";

print join "\n", map { (stat)[1] } @ARGV,"\n" 
Sobrique
  • 52,974
  • 7
  • 60
  • 101