Monday, August 3, 2009

using strict

STRICT:-
It ensures that you pre-declare your variables, don;t have barewords and don;t use symbolic references. It also saves from making accidental spelling mistakes:
#without strict;
$num_friend = 2;
print " I have $num_friends \n"; #oops wrong spelling

if you have used strict then case will die with error
Global symbol "$num_friends" requires explicit package name.

A bareword is any combination of letters, numbers, and underscores, and is not qualified by any symbols. That is, while $apple is a scalar and @apple is an array, while apple is a bareword.

There are a couple of areas in Perl where a bareword is allowed. A bareword string does not need to be qualified with quotes, and a subroutine doesn't always need the &. However in most of the cases taking these shortcuts leads to less readable code.

use strict;
use warnings;

sub say_hi {
my $first = shift;
my $name = shift;

print $first, $name, "\n";
return;
}

&say_hi("hi", "gkg");


But you should be aware that there are more than one way of calling a subroutine. In this case since we have already defined the subroutine so we don't need to prefaec it with &, and it can also be called as
say_hi("hi", "GKG."); #valid but not a correct way.

here you can also call it as:
say_hi "hi" , "GKG" ; #valid, but not a good way of coding

say_hi ; #valid, just prints new line character, no params in, just a bareword

while above command can be written in more readable way as :
&say_hi();

but there are some commands where parentheses are invalid:
#Valid syntax
print OUTPUT_FH $message, $name,"\n";

#Invalid Syntax
print(OUTPUT_FILE $message, $name, "\n");
parentheses indicates a list for print and needs comma between each paarmeter

#Okay but weird
print OUTPUT_FILE ($message, $name, "\n");

>>Use qoutes for strings.
>>Always call your subroutines with & and (), even if there are no args.
but when you are using "qw" then there is no need to have qoutes for variables inside a list.

Symbolic references:

the variable $var indicates that $var is a reference variable,and it is expected that the value will be returned to the variable referenced by $var when reference was taken. But if $var is not a refernce variable at all? then Perl tries to check whether it contains any string, if yes then perl mess around with this string.

$x = 0;
$var = "x";
$$var = 30; # Modifies $x to 30 , because $var is a symbolic reference !

so to avoid this situation you can use

use strict 'refs'; # Tell Perl not to allow symbolic references
$var = "x";
$$var = 30;

Strict refs will remain activated tillthe end of block, but it can be deactivated by saying,
no strict; # or
no strict 'refs';

for more on symbolic references refer to chapter 8.4 "Programming Perl" 3rd edition, O'relly.
or perldoc perlref .

No comments:

Post a Comment