Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Lexicals vs package vars

by LanX (Saint)
on Nov 20, 2008 at 14:08 UTC ( [id://724880]=note: print w/replies, xml ) Need Help??


in reply to Re^2: Indirect variable name
in thread Indirect variable name

to make it a bit less technical, the lexical variables are much younger in perl history than the package variables, dating back to perl 4 3 2 1 or older.

Lexicals are by definition private to the lexical block, marked by { curlies }. You can rely on that they will be destroyed after leaving the block! This "hiddeness" is a quality (!) package-vars do not have. (*)

(Note: The biggest possible block is the containing file, and you could prolong the lifetime by returning references - thats also a matter of garbage collection and closures and ... getting to far)

Package variables OTH have the quality to be as global as possible, if you know the packagename you can access them from everywhere in the program, any file.

So lexicals can't be in the stash associated to a package!!! If you want to inspect them you need to hack with moduls like padwalker.

Saying that lexicals are "much younger", explains some inconsequences / inorthogonalities of perls syntax.

e.g. you can (without extra non-core moduls) only alias a packagevar $a directly with globs * eg *a=$b but not lexical vars ...

... which leads to the problem that you end using hashrefs and arrayrefs as returnvalues

... which as a consequence complicate the sourcecode cluttered with dereferencing syntax

my ($arr_ref)=func(); push @{ $arr_ref->[1][2] }, "elem"; # hate this @{}

... sigh!!! O Perl 6! Where art thou!!!

Cheers LanX

UPDATES:

(*) neither Python AFAIK

MENMONIC: because packagevars are as global as possible they are ours, meanwhile lexicals belong privately to the block/sub, they are "my-ne". ; )

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://724880]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (1)
As of 2024-04-25 00:04 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found