in reply to File manipulation only works when I split it into two files.

First, you should always use strict; and use warnings;. Second, you should use lexical file handles. Third, you can perform this in one loop over the file. And fourth, you can use unlink to delete the file, and rename to rename the temp file.

This should do what you want:

#!/usr/bin/perl use strict; use warnings; open my $file, "<", "petpages" or die "Could not open petpages: $!"; open my $new, ">", "petpages.new" or die "Could not open petpages.new: + $!"; while (my $line = <$file>) { $line =~ tr/A-Z/a-z/; print $new "http://$line"; } close $file; close $new; rename "petpages.new", "petpages";

Update:I forgot to mention that exec doesn't do what you think. As the first line in the doc says, exec never returns. That is why you got the warning: Statement unlikely to be reached at c.pl line 11. (Maybe you meant system() when you said exec()?). Since the rest of the code is never executed, that is why the "http://" never gets prepended.

Replies are listed 'Best First'.
Re^2: File manipulation only works when I split it into two files.
by Anonymous Monk on Dec 03, 2008 at 01:09 UTC

    Ah, nice, that does it. I vaguely remember trying to do it in one loop over but I don't remember how I did that. It didn't work, anyway.

    Thank you.

      Doing it in one loop:

      #!/usr/bin/perl -w use strict; die "Usage: ", $0 =~ /([^\/]+)$/, " <filename>\n" unless @ARGV; $^I = ''; # We're really brave - no backup file! + while (<>){ next unless /./; # Skip empty lines tr/A-Z/a-z/; # Lowercase the lot s#^(?!http://)#http://#; # Prefix 'http://' if one is missing print; }

      If 'petpages' contains the following:

      foobar.com http://foo.int fOoBaR.nEt FoObAr.OrG

      then running the above script with 'petpages' as an argument results in the content being changed to this:

      http://foobar.com http://foo.int http://foobar.net http://foobar.org

      Update: Clarified phrasing a bit.


      --
      "Language shapes the way we think, and determines what we can think about."
      -- B. L. Whorf