Playing with shift , @_ , $_

The ‘Shift’ function pops the first element of an array and returns the popped item to the left side variable. There is a way to write cryptic code with “shift”, to impress your family (yep.. only family, sorry). Perl has some internal default variables that get initialized when in some sub routine. Lets say you’re passing an array of elements to some sub routine. You don’t need an explicit variable like in some languages to store that passed variable. You can directly use the implicit variables for getting the passed parameters. Let’s write a subroutine using some implicit variables and “shift”:

sub printFileContent {


printInsideThings ($_);

sub printInsideThings {
open FILE,$_;
while($line = <FILE>){
print $line;

printFileContent (“C:\\Data\\virtual-hosting-howto.html”,”C:\\Data\\virtual-boasting-howto.html”);

As I pass a list of files, the ‘@_’ of my first sub is already initialized with the list of strings that I passed.
So I used ‘foreach’ and passed the “$_” to another subroutine. The ‘$_’ will be initialized to the list item for
each iteration over the list. The other sub takes the string, and using a ‘$_’, which is initialized with the passed value by default, it opens the file and initializes a global variable ‘FILE’ and prints the content line by line in the while loop. The ‘< >’ opens the file and reads it line by line for you (uber cool tool eh?). Other ways we can do the later subroutine:

sub printInsideThings {
open FILE,shift;
print ;

Look at the while loop there. Perl uses the ‘$_’ so implicitly that you don’t even have to specify it. That loop initializes the ‘$_’ for every iteration and assigns it the line it reads from the file. The “print;” is equivalent to “print $_;” Again, the ‘shift’ in that file opener takes out the first of the ‘@_’ and passes it for parsing stuff

This one prints the contents of a single file that is passed:

sub openFu{
open FILE, shift;

openFu “c:\\data\\virtual-hosting-howto.html”;


Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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: