Input and output (I/O) operations are fundamental to any programming language, and Perl is no exception. These operations allow you to interact with users, read from files, and write data to external sources.
Perl provides built-in functions for handling standard input and output:
print()
: Outputs data to the console<>
(diamond operator): Reads input from the user or a file
print "Enter your name: ";
my $name = <>;
chomp($name); # Remove newline character
print "Hello, $name!\n";
Perl offers robust file handling capabilities. Here's a quick overview:
Use the open()
function to create a file handle:
open(my $fh, '<', 'input.txt') or die "Cannot open file: $!";
The second argument specifies the mode: '<' for reading, '>' for writing, and '>>' for appending.
while (my $line = <$fh>) {
chomp($line);
print "Read: $line\n";
}
open(my $fh, '>', 'output.txt') or die "Cannot open file: $!";
print $fh "Hello, World!\n";
close($fh);
open()
for better securityAs you progress, you'll encounter more advanced I/O concepts in Perl:
Understanding these I/O operations is crucial for developing robust Perl applications that interact with external data sources and users effectively.
For more information on related topics, check out these guides: