search instagram arrow-down

Archives

Categories

Meta

Input/Output

Standard Input
$line = <STDIN>;        # read the next line
chomp($line);           # and chomp it
chomp($line = <STDIN>); # same thing, more idiomatically

”’For array”’
@myarray = <stdin>
press Ctrl-D when done.

”’Diamond operator <>”’
<> operator is used if you want to make a perl program that can be used like the UNIX utilities such as cat, sed, awk, sort, grep lpr etc. The diamond operator is actually a special kind of line input operator. But instead of getting the input from the keyboard, it comes from the user’s choice of input.
while (defined($line = <>)) {
chomp($line);
print “$line\n”;
}
This program when executed with a filename as arguments will print the content of file line by line as of cat.
$line = <STDIN>;        # read the next line
chomp($line);           # and chomp it
chomp($line = <STDIN>); # same thing, more idiomatically

Since the line-input operator will return undef when you reach end-of-file, this is handy for dropping out of loops:

while (defined($line = <STDIN>)) {
print “I saw $line”;
}
shortcut
while (<STDIN>) {
print “I saw $_”;
}

This entry was posted in Perl.
Leave a Reply
Your email address will not be published. Required fields are marked *

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: