Horje
perl input output Code Example
perl input output
# Basic syntax:
# For reading:
open(my $in, "<", "infile.txt") or die "Can't open infile.txt: $!";
# For writing (overwrites file if it exists):
open(my $out, ">", "output.txt") or die "Can't open output.txt: $!";
# For writing (appends to end of file if it exists):
open(my $log, ">>", "my.log") or die "Can't open my.log: $!";
# Where:
# 	The first argument to open creates a named filehandle that can be
#		referred to later
#	The second argument determines how the file will be opened
#	The third argument is the file name (use $ARGV[#] if reading from the CLI)
#	The or die "" portion is what to print if there is an error opening the file
# Note, be sure to close the filehandle after you're done operating on the file:
close $in;

# You can read from an open filehandle using the "<>" operator.  In
# scalar context it reads a single line from the filehandle, and in list
# context it reads the whole file in, assigning each line to an element
# of the list:
my $line = <$in>;
my @lines = <$in>;

# You can iterate through the lines in a file one at a time with a while loop:
while (my $line = <$in>) {
  print "Found apples\n" if $line =~ m/apples/;
}

# You can write to an open filehandle using the standard "print" function:
print $out @lines;
print $log $msg, "\n";




14

Related
perl foreach loop Code Example perl foreach loop Code Example
perl print an array Code Example perl print an array Code Example
perl math operators Code Example perl math operators Code Example
perl add to hash Code Example perl add to hash Code Example
perl if else Code Example perl if else Code Example

Type:
Code Example
Category:
Coding
Sub Category:
Code Example
Uploaded by:
Admin
Views:
10