in reply to Capture Contents AND Overwrite without Opening Twice?

Hey Guys,

So I got the Tie::File working in my script, in the previous post I had it working in a test script.

Below is the section of my script where I use the tie() function. Basically, my script opens a socket and sits
and waits for a remote server to make a connection. Once the socket connection is made, my script captures
the data sent from the remote server (*Hostname, IP Addr, Timestamp, and Location Name). Before the code
below I check all the contents of those 4 variables. In the code below, I format a New Line of data (*$new_data),
then I check and see if either the File/Array is empty (== -1) or if the 1st element in the Array does not contain
the Header Text. If it doesn't, I use unshift and add it to the start of the array/file.

I have run a few tests and it all seems to be working very well... I'm really liking the Tie::File Module, so thanks
for showing that to me.!

### Check and make sure ALL the variables contain values and are NOT = += ERROR: if ($ipAddr !~ /ERROR/i && $hostname !~ /ERROR/i && $location !~ /ERRO +R/i && $timestamp !~ /ERROR/i) { ### Declare the Log File: my $LOG_FILE = "$LOG_DIR/$hostname.log"; ### build the line to print to the LogFile: # *MAX COLUMN WIDTHS --> Timestamp(24) Location(14) IP Addr +ess(15) Hostname(18) my $new_data = sprintf "%-25s %-15s %-16s %-19s", "$timestam +p", "$location", "$ipAddr", "$hostname"; ### Open the Log File and "TIE" it to the array @logData: # *With this (*Tie::File) whatever happens to the array is refl +ected in the file: tie my @logData, 'Tie::File', "$LOG_FILE" or die "Error: tie faile +d, $!"; ### If the File/Array is empty --OR-- THe first element does not c +ontain the LOG_HEADER, then... if ($#logData == -1 || $logData[0] !~ /LAST CHECK|LOCATION|IP ADDR +ESS|HOSTNAME/gi) { ### Insert the LOG_HEADER as element '0' in the array: unshift @logData, "$LOG_HEADER"; } ### If @logData has more lines then MAXLINES, then Splice out X li +nes starting at Line 2 (*i.e. index '1') splice @logData, 1, @logData-$MAXLINES if @logData>$MAXLINES; ### Next, push the new data onto the end of the Array/File: push @logData, "$new_data\n"; ### Untie the Array from the Log File (*essentially closing the fi +le...): untie @logData; }

So, thanks AGAIN everybody for the help, very much appreciated!!

Thanks,
Matt

Replies are listed 'Best First'.
Re^2: Capture Contents AND Overwrite without Opening Twice?
by Anonymous Monk on Oct 09, 2014 at 19:24 UTC

    Looks good, thanks for sharing!

    (The only very minor nit I might pick is that you don't need to interpolate your variables into a string in a couple of places, such as "$LOG_FILE"; just saying $LOG_FILE is fine.)