in reply to Opening a file for reading or writing (was: Newbie)

Here is something wich should work. It litle big but you can cut it.

# -------------------------------------------------------------------- +----- # read array from file sub read_file { my ( $line ); if ( not open(FILE, $file_path) ) { &logging( "Can't open database file." ); die; } if ( $file_lock ) { flock(FILE, 1); } @file = (); while ( $line = <FILE> ) { chomp($line); push(@file, $line); } } <p>
Now you can do anything you want with array @file.

# -------------------------------------------------------------------- +----- # write array back to file sub write_file { my ( $line ); if ( not open(FILE, ">".$file_path) ) { &logging( "Can't open database file." ); die; } if ( $file_lock ) { flock(FILE, 2); } foreach $line ( @file ) { print FILE "$line\n"; } close(FILE); }

if $file_lock is <> 0 then script will use file locking.

Li Tin O've Weedle
mad Tsort's philosopher

Replies are listed 'Best First'.
Re (tilly) 2: Opening a file for reading or writing (was: Newbie)
by tilly (Archbishop) on Mar 18, 2001 at 20:07 UTC
    First of all useful error messages should always preserve whatever information you can get on what went wrong. In this case that means you shouldn't lose the filename and contents of $!.

    Secondly your file locking makes all of the usual mistakes and will be subject to all of the regular race conditions. You need to put your locks around the entire sequence of actions that should be an atomic unit. There have been several threads on this before, see Re (tilly) 1: Flock Feedback for an example.