Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I find a filename from a filehandle in Perl?

Tags:

open(my $fh, '>', $path) || die $!; my_sub($fh); 

Can my_sub() somehow extrapolate $path from $fh?

like image 227
sh-beta Avatar asked May 11 '10 17:05

sh-beta


People also ask

How do I use FileHandle in Perl?

The three basic FileHandles in Perl are STDIN, STDOUT, and STDERR, which represent Standard Input, Standard Output, and Standard Error devices respectively. File Handling is usually done through the open function. Syntax: open(FileHandle, Mode, FileName);

How do I access a file in Perl?

You use open() function to open files. The open() function has three arguments: Filehandle that associates with the file. Mode : you can open a file for reading, writing or appending.

What is FH in Perl?

The $fh (file handle) is a scalar variable and we can define it inside or before the open() function. Here we have define it inside the function. The '>' sign means we are opening this file for writing. The $filename denotes the path or file location. Once file is open, use $fh in print statement.


2 Answers

A filehandle might not even be connected to a file but instead to a network socket or a pipe hooked to the standard output of a child process.

If you want to associate handles with paths your code opens, use a hash and the fileno operator, e.g.,

my %fileno2path;  sub myopen {   my($path) = @_;    open my $fh, "<", $path or die "$0: open: $!";    $fileno2path{fileno $fh} = $path;   $fh; }  sub myclose {   my($fh) = @_;   delete $fileno2path{fileno $fh};   close $fh or warn "$0: close: $!"; }  sub path {   my($fh) = @_;   $fileno2path{fileno $fh}; } 
like image 96
Greg Bacon Avatar answered Oct 05 '22 08:10

Greg Bacon


Whoever might be looking for better way to find the file name from filehandle or file descriptor:

I would prefer to use the find -inum , if available. Or, how about using following way, always - any drawbacks except the unix/linux compatible!

my $filename='/tmp/tmp.txt'; open my $fh, '>', $filename; my $fd = fileno $fh; print readlink("/proc/$$/fd/$fd"); 
like image 32
Subba Reddy Avatar answered Oct 05 '22 08:10

Subba Reddy