Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re^2: While loop not printing anything after using grep

by skjeiu (Novice)
on Dec 30, 2020 at 14:13 UTC ( [id://11125996]=note: print w/replies, xml ) Need Help??


in reply to Re: While loop not printing anything after using grep
in thread While loop not printing anything after using grep


Following the constructive feedback here is the working code:

#!/bin/perl use strict; use warnings; my $input_file = 'input.txt'; my $output_file = 'output.txt'; open(my $in_file,'<', $input_file) or die "Can not open file $input_fi +le for writing: $!.\n"; open(my $out_file,'>', $output_file) or die "Can not open file $output +_file for writing: $!.\n"; if (not (grep{/Monday/} <$in_file>) { seek $in_file, 0, 0; $. = 0; while (<$in_file>) { print $out_file $_; if ($. == 1) { print $out_file "Friday\n"; } } } close($in_file); close($out_file);


The same code but with 'unless' instead of 'if (not)'

#!/bin/perl use strict; use warnings; my $input_file = 'input.txt'; my $output_file = 'output.txt'; open(my $in_file,'<', $input_file) or die "Can not open file $input_fi +le for writing: $!.\n"; open(my $out_file,'>', $output_file) or die "Can not open file $output +_file for writing: $!.\n"; unless (grep{/Monday/} <$in_file>) { seek $in_file, 0, 0; $. = 0; while (<$in_file>) { print $out_file $_; if ($. == 1) { print $out_file "Friday\n"; } } } close($in_file); close($out_file);


As 'seek' could probably be avoided if I rethink things in a different way, I'll get back to this when I have clarified my thoughts


I appriciated

Replies are listed 'Best First'.
Re^3: While loop not printing anything after using grep
by AnomalousMonk (Archbishop) on Dec 31, 2020 at 00:10 UTC
    open(my $in_file,'<', ...) or die "Can not open ... for writing: $!.\n";

    <nit>
    $in_file is being opened for reading ('<'), not writing.
    </nit>


    Give a man a fish:  <%-{-{-{-<

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11125996]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (1)
As of 2024-04-26 02:42 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found