in reply to Re^5: Access a global variable from a subroutine when used as "for" iterator
in thread Access a global variable from a subroutine when used as "for" iterator
Your perception of my as global is also wrong !
Only special variables like $_, $a, $" are really global (they always belong to the main:: namespace).
Package variables are "public", but often protected by the need to fully qualify them, like 'pck::name'.
my's are private to the lexical scope, which is at most the file scope, which some people try to describe as "file-global".
our is a way to define a lexical shortcut to a package var.
(maybe I should start writing a tutorial instead of preaching again and again ;)
In your case I'd suggest using package vars, because you can easily access the vars after exporting the subs.
The following demo is explicitly using two packages to fake an import situation. you can simplify it in a one-file-for-all situation. But it should help you grasp the differences between different var types.
use v5.14; use warnings; { package _csv; # some package name our $row; our $col; sub c { my $c = shift // $col // die "col undefined"; my $r = shift // $row // die "row undefined"; say "c:$c r:$r"; } say "--- inside same scope"; for $row (1..3) { c("A"); } } package main; BEGIN { *c = \&_csv::c } # fake import for demo say "--- one default"; for $_csv::row (1..3) { c("B"); } say "--- two defaults"; for $_csv::col ("C".."D") { for $_csv::row (4..5) { c(); } } say "--- explicit local "; { local $_csv::row = 10; c("E"); c("F"); } say "--- defaults were localized inside loop"; c("G");
perl ~/perl/cell_dsl.pl --- inside same scope c:A r:1 c:A r:2 c:A r:3 --- one default c:B r:1 c:B r:2 c:B r:3 --- two defaults c:C r:4 c:C r:5 c:D r:4 c:D r:5 --- explicit local c:E r:10 c:F r:10 --- defaults were localized inside loop row undefined at /home/lanx/perl/cell_dsl.pl line 12.
But frankly, if I were you, I'd rather define multiple subs with special explicit behavior instead of overloading one with implicit DWIM.
Or at least, use them both together and let the implicit one call the explicit ones.
Cheers Rolf
(addicted to the Perl Programming Language :)
see Wikisyntax for the Monastery
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^7: Access a global variable from a subroutine when used as "for" iterator
by vitoco (Hermit) on Dec 22, 2023 at 00:45 UTC | |
by LanX (Saint) on Dec 22, 2023 at 02:24 UTC | |
by hippo (Archbishop) on Dec 22, 2023 at 08:45 UTC | |
by LanX (Saint) on Dec 22, 2023 at 10:14 UTC |