Home arrow Perl Programming arrow Variables and Arguments in Perl

Variables and Arguments in Perl

In this fifth part to a six-part article series on subroutines and functions in Perl, you'll learn about lexical variables, and how passing arguments works. This article was excerpted from chapter six of the book Beginning Perl, Second Edition, written by James Lee (Apress; ISBN: 159059391X).

  1. Variables and Arguments in Perl
  2. Some Important Notes on Passing Arguments
By: Apress Publishing
Rating: starstarstarstarstar / 0
May 02, 2012

print this article



Lexical Variables (aka Local Variables)

The range of effect that a variable has is called its scope, and lexical variables declared with my()are said to have lexical scope. This is also known as local scope. That is, they exist from the point where they’re declared until the end of the enclosing block. The name “lexical” comes from the fact that they’re confined to a well-defined chunk of text.

my $x;
$x = 30;
my $x; # New $x
$x = 50;
# We can’t see the old $x, even if we want to.
print $x; # This $x is, and always has been, 30.

Great. We can now use variables in our subroutines in the knowledge that we’re not going to upset any behavior outside them. Let’s modifyglobal2.plby addingmy()in the function (now calledchange_global_not()):

#!/usr/bin/perl -w
# my.pl

$x = 10;

print "before: $x\n";
print "after: $x\n";

sub change_global_not {
my $x = 20;
print "in change_global_not(): $x\n";

This gives us the output we expect:

$ perl my.pl
before: 10
in change_global_not(): 20
after: 10

>>> More Perl Programming Articles          >>> More By Apress Publishing

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort


- Perl Turns 25
- Lists and Arguments in Perl
- Variables and Arguments in Perl
- Understanding Scope and Packages in Perl
- Arguments and Return Values in Perl
- Invoking Perl Subroutines and Functions
- Subroutines and Functions in Perl
- Perl Basics: Writing and Debugging Programs
- Structure and Statements in Perl
- First Steps in Perl
- Completing Regular Expression Basics
- Modifiers, Boundaries, and Regular Expressio...
- Quantifiers and Other Regular Expression Bas...
- Parsing and Regular Expression Basics
- Hash Functions

Developer Shed Affiliates


Dev Shed Tutorial Topics: