I'm trying to convert a FILEHANDLE to a string so I can search and replace text and then rewrite the file.
#!/usr/bin/perl -w
use strict;
my $file = "/var/www/html/acs/new/index.html";
my $file_bu = "/var/www/html/acs/new/index_bu.html";
open (FILE, "+<$file") or die "Can't open file: $!";
open (FILE_BU, ">$file_bu") or die "Can't open file: $!";
# Save a back up of the original file
my @file = <FILE>;
#print "@file\n";
print FILE_BU "@file";
close FILE_BU;
# Convert file to string for search and replace
my $string = do {local $/; <FILE>};
if (defined $string) {print "defined\n"};
print "$string\n";
close FILE;
Results:
[joev@localhost test]$ ./file_handle.pl
defined
[joev@localhost test]$
Why does nothing get printed out for $string even though it is defined? I expected $string to be printed the same way as print "@file\n";
Is there a better way to accomplish this?
Thanks
Joe
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.