Basic I/O

I/O means "Input/Output". It's how your program communicates with the world.
Output

The print() function does it all:

Code:
#!/usr/bin/perl # file: print.pl $sidekick = 100; print "Maxwell Smart's sidekick is ",$sidekick-1,".\n"; print "If she had a twin, her twin might be called ",2*($sidekick-1),".\n";
Output:

(~) 50% chmod +x print.pl(~) 51% print.plMaxwell Smart's sidekick is 99.If she had a twin, her twin might be called 198.
We will learn later how to print to a file rather than the terminal.
Input

The <> operator does input. It reads a line of input from the terminal. At the point that <> appears, the script will stop and wait for the user to type of line of input. Then <> will copy the input line into a variable.



#!/usr/bin/perl # file: dog_years.pl print "Enter your age: "; $age = <>; print "Your age in dog years is ",$age/7,"\n";
Output:

(~) 50% dog_years.plEnter your age: 42Your age in dog years is 6
We will learn later how to take input from a file rather than the terminal.
The chomp() Function

When <> reads a line of input, the newline character at the end is included. Because of this, the program below doesn't do exactly what you expect:

#!/usr/bin/perl print "Enter your name: "; $name = <>; print "Hello $name, happy to meet you!\n";
Output:

% hello.pl Enter your name: Lincoln Hello Lincoln , happy to meet you!
If you want to get rid of the newline there, you can chomp() it off. chomp() will remove the terminal newline, if there is one, and do nothing if there isn't.This program works right:

#!/usr/bin/perl print "Enter your name: "; $name = <>; chomp $name; print "Hello $name, happy to meet you!\n";
Output:

% hello.pl Enter your name: Lincoln Hello Lincoln, happy to meet you!



› See More: >>Perl Basics 4<<