Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Howto: Use a variable as a file handle. 2

Status
Not open for further replies.

thenewa2x

Programmer
Dec 10, 2002
349
0
0
US
How do you use a variable ($FH) as a file handle?
this doesn't work for me:

Code:
use Fcntl qw(:flock);

fopen(FILE, "test.txt");
fprint(FILE, "some text here....");
fclose(FILE);

sub fopen
{
  my ($CN,$path) = @_;
  open($CN, $mode, $path);
  flock($CN, LOCK_EX);
}
sub fprint
{
  my ($CN,$string) = @_;
  print $CN $string;
}
sub fclose
{
  flock($CN, LOCK_UN);
  close($CN);
}
 
I tried it out, looks like it works! Thanks.
 
NO, it works...

I ran your code and found that you dont have $mode set to anything...and the "open" procedure wants 2 args, the filehandle and an expression...if it starts with ">" or ">>" it will write to the file (what you want..)

Here is the code that works:
Code:
use Fcntl qw(:flock);
fopen("FILE", "test.txt");
fprint("FILE", "some text here....");
fclose("FILE");

sub fopen
{
  my ($CN,$path) = @_;
  open($CN, ">$path");
  flock($CN, LOCK_EX);
}
sub fprint
{
  my ($CN,$string) = @_;
  print $CN $string;
}
sub fclose
{
  flock($CN, LOCK_UN);
  close($CN);
}
 
thanks but it also works like this: fopen(FILE, "test.txt");

now i have another question. does FileHandle have the same functions as open? i would like to know seek and flock.
 
@CadGuyExtraordinaire: misread your last post, just ignore the: thanks but it also works like this: fopen(FILE, "test.txt");
 
Yeah, you can use the FileHandle seek and tell (which are actually just frontends to the regular seek and tell which would also work) :

$fh= new FileHandle;
$fh->seek(0,0);
or just,
seek($fh,0,0);


also you can use the flock on the filehandle created by the FileHandle module:

$fh=new FileHandle;
flock $fh,LOCK_EX;

 
thank you, all posts have been quite helpful.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top