At 08:32 10.07.2001 -0700, Bob Bondi wrote:
>Yep, another newbie at Perl. I have come to a wall. What I need to do is
>open a file, find a value in the file and substitute a value.
>I've gotten to the point of what to do with an open file. I have been trying
>the @array = <testfile> statement.
>I then wanted to verify the contents of the array and tried printing it,
>print("$array\n");
>
>But there is no output is unexpected! 0: is the output.
>
>Also, the substitute thingie is, well, odd. Say, I define $sFind="this.gif",
>and $sSwap="that.gif".
>And say I have an array with each line of a file tucked away in it. What the
>heck is the syntax for it????
... untested, but the comments are what counts :) ...
<code>
#\perl\bin
use strict; # use strict! It will save you many headaches
open(TESTFILE, "/Inetpub/wwwroot/date.htm") || die "Can't open
/Inetpub/wwwroot/date.htm: $!"; # changing open() to read-only
#@array = <TESTFILE>;
# here, you've read the entire file into an array -- this may or may not be
what you want to do. If the file is big, you may be
# leaving yourself open to memory problems. The best bet is usually to
read through the file one line at a time.
# first, we'll declare your gif variables -- using my now, because we're
using strict.
my $sFindGIF = "this.gif";
my $sSwapGIF = "that.gif";
my $sNewData = ""; # initialize a string that will contain our new data, at
the end of the substituting, we'll close TESTFILE and
# re-open it for writing (I find that easier than
dealing with file pointers
# or you may want to save the data to a new file
(always a good idea)
while(<TESTFILE>)
{
# this will loop through the file, grabbing one line at a time and
throwing it into the $_ variable
print; # this will print your line -- if I don't specify what I
want to print(), Perl assumes $_
# now we do your substitution
s/$sFindGIF/$sSwapGIF/g; # again, Perl assumes $_
$sNewData .= $_; # add the new string to $sNewData
}
close TESTFILE;
open(TESTFILE, ">/Inetpub/wwwroot/date.htm") || die "Can't open
/Inetpub/wwwroot/date.htm: $!"; # now open() with write permission
print TESTFILE $sNewData;
close TESTFILE;
</code>
Just FYI
usually, if you want to loop through an array, you want to use foreach, ie
foreach my $element(@array)
{
}
for ($index = 0; $index<=$#index; $index++) {
if ($array[$index] =~ /sFindGIF/) {
Here, your searching for the string "sFindGIF", not the value contained in
the variable $sFindGIF
print ("$index: $_\n");
$s = $array[$index];
why do you create the variables and then not use them? Use $sFindGIF and
$sSwapGIF here.
$s =~ s/this.gif/that.gif/;
close (TESTFILE);
Aaron Craig
Programming
iSoftitler.com