Perl, lesson 3
Standard input (stdin) is the text fed into your program, such as the Input box when you run
code here. In Perl it's available through the filehandle STDIN.
Put a filehandle in angle brackets to read from it. In scalar context, <STDIN> reads the
next line:
The line you get back includes the line break at the end. chomp removes it. Forget the
chomp and your output will have a surprise new line in the middle. A common short form
declares, reads and chomps in one go:
When there is nothing left to read, <STDIN> returns undef.
Perl doesn't need you to convert text to numbers. If a string looks like a number, using it with a numeric operator treats it as one:
2 exercises to try what you just read.
Leading spaces are fine. If the text is not a number at all, Perl uses 0 and (with
use warnings) prints a warning on stderr.
When several numbers share a line, split breaks the line into a list. split ' ', $line
splits on any run of whitespace and ignores leading spaces:
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ - * | add, subtract, multiply | 7 * 2 | 14 |
/ | division (keeps the fraction) | 7 / 2 | 3.5 |
% | remainder of whole numbers | 7 % 2 | 1 |
** | power | 2 ** 10 | 1024 |
There is no separate integer division operator. Use int() to drop the fraction:
int(7 / 2) is 3. int cuts toward zero, so int(-3.5) is -3.
Precedence works as in maths: ** first, then *, /, %, then + and -. Use
parentheses to make anything else clear.
printf prints using a format template, and sprintf returns the formatted string instead
of printing it. %d is a whole number, %s a string and %.2f a number with two decimals:
A group of friends shares a pizza. Read the number of slices on the first line and the number of friends on the second line (always at least 1). Everyone gets the same whole number of slices, and the rest stays in the box. Print:
Sample input:
Sample output:
Read a temperature in Celsius (it may have a decimal point) and print it in Fahrenheit with
exactly one decimal place. The formula is F = C * 9 / 5 + 32.
Sample input:
Sample output:
Print the Celsius value exactly as it was typed.
use strict;
use warnings;
my $name = <STDIN>;
chomp $name;
print "Hello, $name!\n";chomp(my $name = <STDIN>);chomp(my $a = <STDIN>); # "7"
chomp(my $b = <STDIN>); # "5"
print $a + $b, "\n"; # 12my ($w, $h) = split ' ', <STDIN>;
print $w * $h, "\n";printf "Average: %.2f\n", 10 / 3; # Average: 3.33
my $label = sprintf "%d items", 4; # "4 items"Each friend gets <n> slices
Leftover: <m>10
3Each friend gets 3 slices
Leftover: 121.521.5 C = 70.7 F