From ff362fc01fa798727c8423d20f093e25702af52b Mon Sep 17 00:00:00 2001 From: Dan Book Date: Sat, 21 Jan 2017 06:06:52 -0500 Subject: [PATCH] [perl/en] how to write to files (#2633) --- perl.html.markdown | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/perl.html.markdown b/perl.html.markdown index 3cbd2801..908f300b 100644 --- a/perl.html.markdown +++ b/perl.html.markdown @@ -170,8 +170,11 @@ $x =~ s/foo/bar/g; # replaces ALL INSTANCES of foo with bar in $x # You can open a file for input or output using the "open()" function. +# For reading: open(my $in, "<", "input.txt") or die "Can't open input.txt: $!"; +# For writing (clears file if it exists): open(my $out, ">", "output.txt") or die "Can't open output.txt: $!"; +# For writing (appends to end of file): open(my $log, ">>", "my.log") or die "Can't open my.log: $!"; # You can read from an open filehandle using the "<>" operator. In @@ -182,6 +185,12 @@ open(my $log, ">>", "my.log") or die "Can't open my.log: $!"; my $line = <$in>; my @lines = <$in>; +# You can write to an open filehandle using the standard "print" +# function. + +print $out @lines; +print $log $msg, "\n"; + #### Writing subroutines # Writing subroutines is easy: