biancoari has asked for the wisdom of the Perl Monks concerning the following question:

Hi everyone, I have this code that makes some changes from a file to the content of it, is there a way to modify that file so the output is printed on a new file, instead of printing the output on the screen.

Here is the code I have:

#!/usr/local/bin/perl open my $FILE, '<', 'rapipago.txt' or die "Cannot open file1.txt: $!"; use strict; use warnings; use feature 'say'; while (my $text = <$FILE>) { chomp $text; my @cums = (0); my @offs = ( 17, 6, 31, 3, 3 ); my @cums = ( 0 ); push @cums, $_ + $cums[ -1 ] for @offs; substr $text, $_, 0, q{-} for reverse @cums[ 1 .. $#cums ]; say $text; }

Replies are listed 'Best First'.
Re: How to modify a file
by Random_Walk (Prior) on Apr 25, 2013 at 13:42 UTC

    Of course. Perl can do anything :)

    # Add this somewhere before the loop # open output file my $outfile = "some_filename.ext"; open my $out, '>', $outfile or die "can't open $outfile: $!\n";

    then change say $text; to say $out $text;. Look out!, there is no comma, between the output file handle and the data you want to send to it.

    Cheers,
    R.

    Pereant, qui ante nos nostra dixerunt!
      One small note... with only one '>' in the open line, the file will be overwritten each time this script runs. If you want to create a file to write to *or append to it if it exists already* be sure to use 2 '>>' instead.

      Here's how I do it:
      my $logfile = "/var/log/my.log" my $text = "Log entry text!" open(LOG, ">>$logfile") or die "Could not open file: $!"; print LOG $text; close LOG;

      Hi, I made this modification:

      #!/usr/local/bin/perl open my $FILE, '<', 'rapipago.txt' or die "Cannot open file1.txt: $!"; my $outfile = "rapipagomod.txt"; open my $out, '>', $outfile or die "can't open $outfile: $!\n"; use strict; use warnings; use feature 'say'; while (my $text = <$FILE>) { chomp $text; my @cums = (0); my @offs = ( 17, 6, 31, 3, 3 ); my @cums = ( 0 ); push @cums, $_ + $cums[ -1 ] for @offs; substr $text, $_, 0, q{-} for reverse @cums[ 1 .. $#cums ]; say $outfile $text; }

      And I am receiving this error:
      "Can't use string ("rapipagomod.txt")as a symbol ref while "strict refs" in use at C:\Users\ARIBIA~1\Desktop\Rapipago.pl line 15, <$FILE> line1."

        $outfile is the filename. You need to use the file handle $out.

        say $out $text;

        poj

Re: How to modify a file
by BillKSmith (Monsignor) on Apr 25, 2013 at 14:28 UTC
    See the runtime flags p and perhaps i in perlrun
    Bill