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". ; )


In reply to Lexicals vs package vars by LanX
in thread Indirect variable name by FreakyGreenLeaky

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.