UseStrict Consulting

Professional IT Solutions & Training

UseStrict Consulting - Professional IT Solutions & Training

Perl Crash Course: Basic I/O

author: Valeria Paixão
revision: André Batosti
enhancement/translation: Vinny Alves

Note from UseStrict: Some of the examples in this tutorial were borrowed from Randall Schwartz’s Learning Perl. It’s a book that EVERY beginner Perl programmer should have. If you don’t have a hardcopy, please consider getting one. You can find it here: Learning Perl, 5th Edition

 

In this article, you will learn how to use basic I/O in Perl, learn about @ARGV, and become familiar with string formatting using printf.

STDIN

<STDIN> tells Perl to read from the standard input – usually the keyboard.

while (defined($_ = <STDIN>)) {
	print "I saw $_";  # echoes whatever is typed onto the screen. 
                                # Quit with ^D or ^Z (depending on your system)
}

foreach (<STDIN>) { 
        print "I saw $_"; # almost the same as above
} 

The difference between the while and foreach loops above is that while executes its statements at every hit of the return key, while foreach slurps into memory all the input until eof (^D on Unixes) and only then executes its instructions.

It is important to note this difference if you don’t want to crash your machine. If your input comes from a webserver with a 400MB log file, you’re better off processing each line individually than slurping it all into memory.
Continue reading

Perl Crash Course: Subroutines

Introduction

Subroutines are user-created functions that execute a block of code at any given place in your program. It is a best practice, however, to aggregate them all either at the beginning or the end the main program.

Subroutine declarations initiate with the key word “sub” . Conventionally, subroutine names are all lowercase characters

sub NAME (PROTOTYPE) BLOCK

print_hello; # subroutine can be executed/called before the actual block is created

sub print_hello {
      print "Hello world\n";
}

When we called print_hello we told Perl that we wanted the piece of code named print_hello to be executed. The result is a “Hello World” showing up on our screen. The only benefit we have from that snippet in its current form is that we won’t have to copy/paste the print statement all over our script if we want to repeat it. All we need to do is call print_hello;
Continue reading

%d bloggers like this: