[7782] in Perl-Users-Digest
Perl-Users Digest, Issue: 1407 Volume: 8
daemon@ATHENA.MIT.EDU (Perl-Users Digest)
Thu Dec 4 16:16:20 1997
Date: Thu, 4 Dec 97 13:00:27 -0800
From: Perl-Users Digest <Perl-Users-Request@ruby.OCE.ORST.EDU>
To: Perl-Users@ruby.OCE.ORST.EDU (Perl-Users Digest)
Perl-Users Digest Thu, 4 Dec 1997 Volume: 8 Number: 1407
Today's topics:
Re: 'Middle of String' sort revisited <rra@stanford.edu>
Re: 'Middle of String' sort revisited <rootbeer@teleport.com>
... rumours run amok (Mike Stok)
Re: Best match in perl? (Mick Farmer)
Bizarre possible perl bug -- help! <mreimer@vpop.net>
Re: Bug in perl5.00404: strange behaviour of eval qx{} <mreimer@vpop.net>
CPAN on CD is not evil (was Re: Resource Kit Anomaly) <Russell_Schulz@locutus.ofB.ORG>
do EventServer.pm, posix.pm work on win32 platform? <kweiner@bloomberg.com>
does EventServer.pm, posix.pm work on win32 platform? <kweiner@bloomberg.com>
eval <hold@cglis.com>
Re: How about a new type of "OR" (lazy evaluation)? <tchrist@mox.perl.com>
Re: if ( ($a{$b}{$c} > $d ... Newby Question (Mick Farmer)
Re: if ( ($a{$b}{$c} > $d ... Newby Question (David Grove)
Re: Joys of tainting (Andrew M. Langmead)
mass mailings from Perl: fonts? <prl2@lehigh.edu>
Re: need the skinny on my() vs local() (Mike Stok)
Re: need the skinny on my() vs local() <tchrist@mox.perl.com>
Re: need the skinny on my() vs local() (Faust Gertz)
Re: Perl4 is not Y2K (was Re: Forced to use brain-dead (I R A Aggie)
Re: Perl4 is not Y2K (was Re: Forced to use brain-dead (M.J.T. Guy)
Re: perlop clarification request (M.J.T. Guy)
Re: problem with odd number of elements in hash table <rootbeer@teleport.com>
Re: Q: lambda fun, loop, string to expr (Ilya Zakharevich)
Re: Q: multiline <eryq@zeegee.com>
Re: Recommended PERL-book? (Faust Gertz)
Returning Values from a Perl script <mark@seattlelab.com>
Shell command in Perl <Slammy@postoffice.worldnet.att.net>
Tk and Lwp under Activeware (David Grove)
Re: Tk and Lwp under Activeware (Matthew Cravit)
Using Pipe with Fork (ISTD/TD)
Digest Administrivia (Last modified: 8 Mar 97) (Perl-Users-Digest Admin)
----------------------------------------------------------------------
Date: 02 Dec 1997 16:46:37 -0800
From: Russ Allbery <rra@stanford.edu>
Subject: Re: 'Middle of String' sort revisited
Message-Id: <m3zpmjw8wi.fsf@windlord.Stanford.EDU>
cotal <cotal@delphi.com> writes:
> Want to sort an array of links based on a string in the middle, in my case
> the country and state abbreviation (US-...)
[...]
> I've unsuccessfully tried variations of the following;
[...]
> @sorted_contents=sort { substr($a, 59) <=> substr($a, 59) } @contents;
You're using a numeric comparator and you're comparing strings; that's
never going to work right. Using cmp instead of <=> will help a lot.
Beyond that, I think what you really want to do is write a sub that
extracts the appropriate string with a regex match or something else from
both $a and $b and then returns the result of cmp applied to them.
You can then optimize with the Schwartzian Transform if you need to.
--
#!/usr/bin/perl -- Russ Allbery, Just Another Perl Hacker
$^=q;@!>~|{>krw>yn{u<$$<[~||<Juukn{=,<S~|}<Jwx}qn{<Yn{u<Qjltn{ > 0gFzD gD,
00Fz, 0,,( 0hF 0g)F/=, 0> "L$/GEIFewe{,$/ 0C$~> "@=,m,|,(e 0.), 01,pnn,y{
rw} >;,$0=q,$,,($_=$^)=~y,$/ C-~><@=\n\r,-~$:-u/ #y,d,s,(\$.),$1,gee,print
------------------------------
Date: Tue, 2 Dec 1997 17:03:22 -0800
From: Tom Phoenix <rootbeer@teleport.com>
To: cotal@delphi.com
Subject: Re: 'Middle of String' sort revisited
Message-Id: <Pine.GSO.3.96.971202165831.19514X-100000@usertest.teleport.com>
On Tue, 2 Dec 1997 cotal@delphi.com wrote:
> Want to sort an array of links based on a string in the middle, in my case
> the country and state abbreviation (US-...)
> What I want to do is find "US-" in each line then print them out in sorted
> order.
Use the Schwartzian Transform, something like this.
@sorted =
map { $_->[0] } # the original element of
sort { $a->[1] cmp $b->[1] } # the sorted list of
map { my $temp = $_;
$temp =~ s/^.*?US-//;
[ $_, $temp ] } # the string and its dopple
@list;
For more information on the S.T., check out this page.
http://www.5sigma.com/perl/schwtr.html
Hope this helps!
--
Tom Phoenix http://www.teleport.com/~rootbeer/
rootbeer@teleport.com PGP Skribu al mi per Esperanto!
Randal Schwartz Case: http://www.rahul.net/jeffrey/ovs/
Ask me about Perl trainings!
------------------------------
Date: 4 Dec 1997 19:18:27 GMT
From: mike@stok.co.uk (Mike Stok)
Subject: ... rumours run amok
Message-Id: <666vm3$jm6@news-central.tiac.net>
In article <666uvg$bfb$1@lyra.csx.cam.ac.uk>,
M.J.T. Guy <mjtg@cus.cam.ac.uk> wrote:
>I R A Aggie <fl_aggie@thepentagon.com> wrote:
>>
>>Well, its too late now. The rumor mill will run with it, and blow it
>>completely out of proportion. Eventually, perl 4 will be blamed for
>>violence, flood, famine, and El Nino.
>
>Not to mention the plague of Camel fleas.
Someone had better tell those fleas to upgrade to the latest version soon
;-)
Mike
--
mike@stok.co.uk | The "`Stok' disclaimers" apply.
http://www.stok.co.uk/~mike/ | PGP fingerprint FE 56 4D 7D 42 1A 4A 9C
http://www.tiac.net/users/stok/ | 65 F3 3F 1D 27 22 B7 41
stok@colltech.com | Collective Technologies (work)
------------------------------
Date: Thu, 4 Dec 1997 14:14:39 GMT
From: mick@picus.dcs.bbk.ac.uk (Mick Farmer)
Subject: Re: Best match in perl?
Message-Id: <EKo4wF.9GK@mail2.ccs.bbk.ac.uk>
Dear Steffen,
Since you're defining the patterns, why not associate a
value with each one that gives the metric you require.
Regards,
Mick
------------------------------
Date: Tue, 02 Dec 1997 13:55:38 -0800
From: Matthew Reimer <mreimer@vpop.net>
To: Joe McDonald <joe@vpop.net>
Subject: Bizarre possible perl bug -- help!
Message-Id: <348483DA.ECF1896A@vpop.net>
I'm having a strange problem with perl where a file-scoped lexical
variable usage inside an eval returns "" unless the variable is somehow
referred to within the subroutine.
For example, running the program below results in the following output:
---
build: var is 0123456789
Use of uninitialized value at (eval 1) line 1.
subst: var is
---
Uncommenting the "$SOME_VAR;" line and running the program gives this:
---
Useless use of private variable in void context at test.pm line 22.
Useless use of private variable in void context at test.pm line 22.
build: var is 0123456789
subst: var is 0123456789
---
I've tested this with perl 5.003, 5.004_01 and 5.004_04 with the same
results.
Is this a perl bug, or am I doing something wrong?
Thanks in advance for any help you can give.
Matt
---file test.pl-------------------------------------
#!/usr/local/bin/perl5.00401 -w
use lib '.';
use test;
&build;
exit;
---file test.pm-------------------------------------
package test;
use Exporter;
@ISA = qw(Exporter);
@EXPORT = qw(build);
use strict;
my $SOME_VAR;
sub build {
$SOME_VAR = "0123456789";
print "build: var is $SOME_VAR\n";
&subst();
}
sub subst {
my $string = 'subst: var is $SOME_VAR';
# $SOME_VAR;
print eval qq/"$string"/, "\n";
}
1;
------------------------------
Date: Thu, 04 Dec 1997 09:38:27 -0800
From: Matthew Reimer <mreimer@vpop.net>
To: Marek.Rouchal@-nospam-hl.siemens.de
Subject: Re: Bug in perl5.00404: strange behaviour of eval qx{}
Message-Id: <3486EA93.5DD52C2B@vpop.net>
I posted a couple of days ago with something that I think is the same
problem.
Here's my post, if it helps find the problem:
=======================
I'm having a strange problem with perl where a file-scoped lexical
variable usage inside an eval returns "" unless the variable is somehow
referred to within the subroutine.
For example, running the program below results in the following output:
---
build: var is 0123456789
Use of uninitialized value at (eval 1) line 1.
subst: var is
---
Uncommenting the "$SOME_VAR;" line and running the program gives this:
---
Useless use of private variable in void context at test.pm line 22.
Useless use of private variable in void context at test.pm line 22.
build: var is 0123456789
subst: var is 0123456789
---
I've tested this with perl 5.003, 5.004_01 and 5.004_04 with the same
results.
Is this a perl bug, or am I doing something wrong?
Thanks in advance for any help you can give.
Matt
---file test.pl-------------------------------------
#!/usr/local/bin/perl5.00401 -w
use lib '.';
use test;
&build;
exit;
---file test.pm-------------------------------------
package test;
use Exporter;
@ISA = qw(Exporter);
@EXPORT = qw(build);
use strict;
my $SOME_VAR;
sub build {
$SOME_VAR = "0123456789";
print "build: var is $SOME_VAR\n";
&subst();
}
sub subst {
my $string = 'subst: var is $SOME_VAR';
# $SOME_VAR;
print eval qq/"$string"/, "\n";
}
1;
==========================
Marek Rouchal wrote:
>
> Please take a minute time and consider this small code snippet:
>
> #!/usr/local/bin/perl -w
>
> sub bla {
>
> #$str = `echo 'print "$_[0]";'`; # line A
> eval `echo 'print "$_[0]";'`; # line B
> #eval $str; # line C
> 1; # line D
> }
>
> $a = "gnu";
> &bla($a);
> __END__
>
> In this state it works as expected, i.e. it prints "gnu".
> If "line D" is commented out, I get a "use of uninitialized value".
> If lines A and C are made valid, and B and D commented out, the
> same "use of uninitialized value" appears. In the latter cases no
> "gnu" is printed.
> Machine: SunOS 5.5.1 Generic sun4u sparc SUNW,Ultra-1
> I reported the bug by perlbug, too.
>
> Kind regards,
>
> Marek
>
> PS. If you want to reply by email, please remove -nospam- from
> the address. Thank you.
>
> --
> Marek Rouchal Phone : +49 89/636-25849
> SIEMENS AG, HL CAD SYS Fax : +49 89/636-23650
> Balanstr. 73 mailto:Marek.Rouchal@-nospam-hl.siemens.de
> 81541 Muenchen PCmail:Marek.Rouchal.PC@-nospam-hl.siemens.de
------------------------------
Date: Thu, 4 Dec 1997 16:54:08 +0000
From: Russell Schulz <Russell_Schulz@locutus.ofB.ORG>
Subject: CPAN on CD is not evil (was Re: Resource Kit Anomaly)
Message-Id: <19971204.165408.1w3.rnr.w164w_-_@locutus.ofB.ORG>
[ why don't people change their Subject: headers? ]
pschon@baste.magibox.net (Peter J. Schoenster) writes:
> "Would you really want to take Web publishing advice from someone who
> had to burn a CD-ROM to distribute his software? Come to
> http://demo.webho.com for electronic versions of the source code
I fail to see how him including a CD-ROM implies that he `had to burn a
CD-ROM to distribute his software'.
not everyone that wants to have a web site, or use CPAN modules, or
for that matter use Perl, has Internet access that is:
- dirt cheap
- ludicrously fast
- available 24 hours per day
obviously, a web site is a great place to get _updates_ for the things
on the CD. but for a lot of people, it's a horrid place to have to
get everything when a $3 CD in the book could have supplied most of it.
obviously, this isn't CPAN- or PRK-specific. `comp.archives.d'?
--
Russell_Schulz@locutus.ofB.ORG Shad 86c
------------------------------
Date: Thu, 04 Dec 1997 14:34:49 -0500
From: kweiner <kweiner@bloomberg.com>
Subject: do EventServer.pm, posix.pm work on win32 platform?
Message-Id: <348705D9.BE8@bloomberg.com>
do EventServer.pm, posix.pm work on win32 platform?
------------------------------
Date: Thu, 04 Dec 1997 14:34:28 -0500
From: kweiner <kweiner@bloomberg.com>
Subject: does EventServer.pm, posix.pm work on win32 platform?
Message-Id: <348705C4.7FDC@bloomberg.com>
does EventServer.pm, posix.pm work on win32 platform?
------------------------------
Date: 3 Dec 97 02:10:16 GMT
From: "Christopher Lambrou" <hold@cglis.com>
Subject: eval
Message-Id: <01bcff90$d77abd10$75712581@akis>
Is it possible to use eval to catch a run time "Out of memory" error?
(I'm thinking since the machine will be out of memory then it won't be able
to continue with next Perl code line)
------------------------------
Date: 4 Dec 1997 18:40:45 GMT
From: Tom Christiansen <tchrist@mox.perl.com>
Subject: Re: How about a new type of "OR" (lazy evaluation)?
Message-Id: <666tfd$m0b$1@csnews.cs.colorado.edu>
[courtesy cc of this posting sent to cited author via email]
In comp.lang.perl.misc,
Joe Klein <jklein@alerts.co.il> writes:
:> $result = &calc(@params) or &default(@params);
:Just a quick comment on the above line - it doesn't work :-(. '=' has a
:higher precedence than 'or'. So what you're really end up doing is:
:
: ($result = &calc(@params)) or &default(@params);
Yes, in retrospect, "or" may have been a design mistake.
--tom
--
Tom Christiansen tchrist@jhereg.perl.com
"If it makes goo on the windshield, we'll call it a bug." --Larry Wall
------------------------------
Date: Thu, 4 Dec 1997 14:20:13 GMT
From: mick@picus.dcs.bbk.ac.uk (Mick Farmer)
Subject: Re: if ( ($a{$b}{$c} > $d ... Newby Question
Message-Id: <EKo55p.9Lw@mail2.ccs.bbk.ac.uk>
Dear Jamie,
The construct $a{$b}{$c} is a shortcut for $a{$b}->{$c},
which means that
1. %a is a hash.
2. The value of $a{$b} is a reference to another (possibly
anonymous) hash.
Regards,
Mick
------------------------------
Date: Thu, 04 Dec 1997 02:23:08 GMT
From: dgrove@ntslink.net (David Grove)
Subject: Re: if ( ($a{$b}{$c} > $d ... Newby Question
Message-Id: <3486132e.14732490@news.ntslink.net>
Use the arrow operators, first of all, and everything becomes a whole
lot clearer!
These are hashes. It's like, they are arrays but the indexes are
strings (or scalars) rather than integers from 0 to n. Like this
$ary[0] = 'a';
$ary[1] = 'b';
$ary[2] = 'c';
...is similar to...
$ary{'0'} = 'a';
$ary{'one'} = 'b';
$ary{2} = 'c';
That should help. If you use the multi dimensional hash reference
thingie, please use the arrows. They aren't required, but I find it
hard to read otherwise.
On Tue, 02 Dec 1997 21:47:28 -0800, Jamie Heller-Evans
<tigger@sgi.com> wrote:
>I am trying to understand this construct:
>
>if ( ($a{$b}{$c} > $d || !$a{$b}{$c}) )
>{
> $a{$b}{$c} = $d;
>}
>
>
>I'm just learning about hashes, but I have never seen
>this kind of syntax before. I don't understand how
>this works, and why the curly braces:
>
> $a{$b}{$c}
>
>and I was wondering if someone could explain it to me.
>I haven't seen this particular construct in any of the
>books I'm using (O'Reilly books, and another by Nigel
>Chapman).
>
>Thanks for your help (in advance),
>
>jamie
------------------------------
Date: Thu, 4 Dec 1997 16:17:06 GMT
From: aml@world.std.com (Andrew M. Langmead)
Subject: Re: Joys of tainting
Message-Id: <EKoAKI.8G1@world.std.com>
fil_nospam@login.net (Philip) writes:
>OK, anybody see the problem with this code :
> next unless($t=~/([a-zA-Z0-9&=\+]+)/); # line 0
> $r=quotemeta($1); # line 1
> $r="$r\\W" if(length($t)<=2); # line 2
>$t is tainted, lines 0 and 1 untaint it in $r. Line 2 causes $r to
>become tainted. If I change line 2 to :
> $r="$r\\W" if(length($1)<=2); # $r is no longer tainted
I don't see that here. I took the code that you posted and put it in
this script:
#!/usr/bin/perl -Tw
$t = shift; # $t starts of tainted
$ENV{PATH} = '/bin:/usr/bin';
next unless($t=~/([a-zA-Z0-9&=\+]+)/); # line 0
$r=quotemeta($1); # line 1
$r="$r\\W" if(length($t)<=2); # line 2
system "echo $r is untainted";
system "echo $t is untainted";
and perl has no complaints about calling system() with $r, but dies on
calling it with $t. (under perl version 5.004)
>From what I can see,
1. yes, $t is tainted.
2. $t is passed to length(). The result of length() is tainted.
3. The tainted result of length() is compared to 2.
4. Depending on the comparison, The assignment to $r is made.
5. The result of length() is thrown away.
--
Andrew Langmead
------------------------------
Date: 4 Dec 1997 19:02:21 GMT
From: "Phil R Lawrence" <prl2@lehigh.edu>
Subject: mass mailings from Perl: fonts?
Message-Id: <01bd00e7$26181600$3e03b480@mm>
I am trying to think of a way to do mass mailing letters from Perl. Maybe
I would grab the names etc from Oracle and stuff them in some hash, then
print the personalized letter for each person.
Big question: Can I use different fonts printing from Perl? I saw the
module Fonts::AFM, would that help? (I looked for this on CPAN to view the
readme, but only found Font-TFM-0.05.readme at
http://www.perl.com/CPAN-local/modules/by-module/Font/ )
How about Pod::Latex? (Again, I looked for the readme, but only found
PodParser-1.02.readme at
http://www.perl.com/CPAN-local/modules/by-category/02_Perl_Core_Modules/Pod/
No help there.)
Thanks.
--
Phil R Lawrence
Systems and Networking Development Services
Programmer/Analyst
prl2@lehigh.edu
------------------------------
Date: 4 Dec 1997 19:33:10 GMT
From: mike@stok.co.uk (Mike Stok)
Subject: Re: need the skinny on my() vs local()
Message-Id: <6670hm$kko@news-central.tiac.net>
In article <666ula$jir@world6.bellatlantic.net>,
Dave Kaufman <davidk@nospam.cnct.com> wrote:
>I was about to paste some functions from a "require" -ed script into my the
>calling script, and forego the require and the need for two files. But I
>see that the functions I'm (ripping off) --copying, use local() to declare
>all the variables, whereas I always use my() to avoid namespace collisions
>from inside functions.
>
>I'm afeared. What is the difference between my() and local() ?
>
>I read the camel book explanation but it sailed right over my pea brain. It
>explained the difference in terms of lexical namespaces, assuming I knew
>what a lexical namespace was :-)
>
>Can someone lend me a clue? Will the world come tumbling down if I change
>those local's to my's? Will Hell freeze over? Will Larry come down and
>thump me on the head? Or will all mankind learn to love one another and
>world peace be finally achieved?
I can't remember what the camel book says, but section 7 of the new FAQ
has this to say:
What's the difference between dynamic and lexical (static)
scoping? Between local() and my()?
local($x) saves away the old value of the global variable
$x, and assigns a new value for the duration of the
subroutine, which is visible in other functions called
from that subroutine. This is done at run-time, so is
called dynamic scoping. local() always affects global
variables, also called package variables or dynamic
variables.
my($x) creates a new variable that is only visible in the
current subroutine. This is done at compile-time, so is
called lexical or static scoping. my() always affects
private variables, also called lexical variables or
(improperly) static(ly scoped) variables.
For instance:
sub visible {
print "var has value $var\n";
}
sub dynamic {
local $var = 'local'; # new temporary value for the still-global
visible(); # variable called $var
}
sub lexical {
my $var = 'private'; # new private variable, $var
visible(); # (invisible outside of sub scope)
}
$var = 'global';
visible(); # prints global
dynamic(); # prints local
lexical(); # prints global
Notice how at no point does the value "private" get
printed. That's because $var only has that value within
the block of the lexical() function, and it is hidden from
called subroutine.
In summary, local() doesn't make what you think of as
private, local variables. It gives a global variable a
temporary value. my() is what you're looking for if you
want private variables.
See also the perlsub manpage, which explains this all in
more detail.
Hope this helps,
Mike
--
mike@stok.co.uk | The "`Stok' disclaimers" apply.
http://www.stok.co.uk/~mike/ | PGP fingerprint FE 56 4D 7D 42 1A 4A 9C
http://www.tiac.net/users/stok/ | 65 F3 3F 1D 27 22 B7 41
stok@colltech.com | Collective Technologies (work)
------------------------------
Date: 4 Dec 1997 19:42:55 GMT
From: Tom Christiansen <tchrist@mox.perl.com>
Subject: Re: need the skinny on my() vs local()
Message-Id: <66713v$q90$1@csnews.cs.colorado.edu>
[courtesy cc of this posting sent to cited author via email]
In comp.lang.perl.misc, "Dave Kaufman" <davidk@cnct.com> writes:
:I was about to paste some functions from a "require" -ed script into my the
:calling script, and forego the require and the need for two files. But I
:see that the functions I'm (ripping off) --copying, use local() to declare
:all the variables, whereas I always use my() to avoid namespace collisions
:from inside functions.
local() doesn't declare anything. Hence your confusion.
:I'm afeared. What is the difference between my() and local() ?
Read perlfaq7 about this. I believe that for each Perl programmer who
understands the difference, there are fully 10,000 who do not. You are
not alone. It's very depressing.
:I read the camel book explanation but it sailed right over my pea brain.
Ok, then don't try to understand, just believe the following:
NEVER USE local() AT ALL (unless you get a syntax error otherwise),
because it doesn't create a local variable; its name is deceiving.
Consider local deprecated, at least for you. Use my instead.
I explain this so many times every day I'm too tired to do it
again now. Well, here; I'll cite myself.
Q: What's the difference between dynamic and lexical (static) scoping?
Between local() and my()?
A: local($x) saves away the old value of the global variable $x,
and assigns a new value for the duration of the subroutine,
which is visible in other functions called from that subroutine.
This is done at run-time, so is called dynamic scoping. local()
always affects global variables, also called package variables
or dynamic variables.
my($x) creates a new variable that is only visible in the current
subroutine. This is done at compile-time, so is called lexical or
static scoping. my() always affects private variables, also called
lexical variables or (improperly) static(ly scoped) variables.
For instance:
sub visible {
print "var has value $var\n";
}
sub dynamic {
local $var = 'local'; # new temporary value for the still-global
visible(); # variable called $var
}
sub lexical {
my $var = 'private'; # new private variable, $var
visible(); # (invisible outside of sub scope)
}
$var = 'global';
visible(); # prints global
dynamic(); # prints local
lexical(); # prints global
Notice how at no point does the value "private" get printed.
That's because $var only has that value within the block of the
lexical() function, and it is hidden from called subroutine.
In summary, local() doesn't make what you think of as private,
local variables. It gives a global variable a temporary value.
my() is what you're looking for if you want private variables.
See also the perlsub manpage, which explains this all in more
detail.
And here the referenced section from perlsub:
Private Variables via my()
Synopsis:
my $foo; # declare $foo lexically local
my (@wid, %get); # declare list of variables local
my $foo = "flurp"; # declare $foo lexical, and init it
my @oof = @bar; # declare @oof lexical, and init it
A "my" declares the listed variables to be confined (lexically)
to the enclosing block, conditional (if/unless/elsif/else),
loop (for/foreach/while/until/continue), subroutine, eval, or
do/require/use'd file. If more than one value is listed, the
list must be placed in parentheses. All listed elements must be
legal lvalues. Only alphanumeric identifiers may be lexically
scoped--magical builtins like $/ must currently be localized with
"local" instead.
Unlike dynamic variables created by the "local" statement, lexical
variables declared with "my" are totally hidden from the outside
world, including any called subroutines (even if it's the same
subroutine called from itself or elsewhere--every call gets its
own copy).
(An eval(), however, can see the lexical variables of the scope
it is being evaluated in so long as the names aren't hidden by
declarations within the eval() itself. See the perlref manpage.)
The parameter list to my() may be assigned to if desired, which
allows you to initialize your variables. (If no initializer
is given for a particular variable, it is created with the
undefined value.) Commonly this is used to name the parameters
to a subroutine. Examples:
$arg = "fred"; # "global" variable
$n = cube_root(27);
print "$arg thinks the root is $n\n";
fred thinks the root is 3
sub cube_root {
my $arg = shift; # name doesn't matter
$arg **= 1/3;
return $arg;
}
The "my" is simply a modifier on something you might assign to. So when
you do assign to the variables in its argument list, the "my" doesn't
change whether those variables is viewed as a scalar or an array. So
my ($foo) = <STDIN>;
my @FOO = <STDIN>;
both supply a list context to the right-hand side, while
my $foo = <STDIN>;
supplies a scalar context. But the following declares only
one variable:
my $foo, $bar = 1;
That has the same effect as
my $foo;
$bar = 1;
The declared variable is not introduced (is not visible) until
after the current statement. Thus,
my $x = $x;
can be used to initialize the new $x with the value of the old $x,
and the expression
my $x = 123 and $x == 123
is false unless the old $x happened to have the value 123.
Lexical scopes of control structures are not bounded precisely
by the braces that delimit their controlled blocks; control
expressions are part of the scope, too. Thus in the loop
while (defined(my $line = <>)) {
$line = lc $line;
} continue {
print $line;
}
the scope of $line extends from its declaration throughout the
rest of the loop construct (including the continue clause),
but not beyond it. Similarly, in the conditional
if ((my $answer = <STDIN>) =~ /^yes$/i) {
user_agrees();
} elsif ($answer =~ /^no$/i) {
user_disagrees();
} else {
chomp $answer;
die "'$answer' is neither 'yes' nor 'no'";
}
the scope of $answer extends from its declaration throughout
the rest of the conditional (including elsif and else clauses,
if any), but not beyond it.
(None of the foregoing applies to if/unless or while/until
modifiers appended to simple statements. Such modifiers are not
control structures and have no effect on scoping.)
The foreach loop defaults to scoping its index variable dynamically
(in the manner of local; see below). However, if the index
variable is prefixed with the keyword "my", then it is lexically
scoped instead. Thus in the loop
for my $i (1, 2, 3) {
some_function();
}
the scope of $i extends to the end of the loop, but not beyond it,
and so the value of $i is unavailable in some_function().
Some users may wish to encourage the use of lexically scoped
variables. As an aid to catching implicit references to package
variables, if you say
use strict 'vars';
then any variable reference from there to the end of the enclosing
block must either refer to a lexical variable, or must be fully
qualified with the package name. A compilation error results
otherwise. An inner block may countermand this with "no strict
'vars'".
A my() has both a compile-time and a run-time effect. At compile
time, the compiler takes notice of it; the principle usefulness
of this is to quiet use strict 'vars'. The actual initialization
is delayed until run time, so it gets executed appropriately;
every time through a loop, for example.
Variables declared with "my" are not part of any package and
are therefore never fully qualified with the package name.
In particular, you're not allowed to try to make a package variable
(or other global) lexical:
my $pack::var; # ERROR! Illegal syntax
my $_; # also illegal (currently)
In fact, a dynamic variable (also known as package or global
variables) are still accessible using the fully qualified ::
notation even while a lexical of the same name is also visible:
package main;
local $x = 10;
my $x = 20;
print "$x and $::x\n";
That will print out 20 and 10.
You may declare "my" variables at the outermost scope of a file
to hide any such identifiers totally from the outside world.
This is similar to C's static variables at the file level.
To do this with a subroutine requires the use of a closure
(anonymous function). If a block (such as an eval(), function,
or package) wants to create a private subroutine that cannot be
called from outside that block, it can declare a lexical variable
containing an anonymous sub reference:
my $secret_version = '1.001-beta';
my $secret_sub = sub { print $secret_version };
&$secret_sub();
So long as the reference is never returned by any function within
the module, no outside module can see the subroutine, because
its name is not in any package's symbol table. Remember that
it's not REALLY called $some_pack::secret_version or anything;
it's just $secret_version, unqualified and unqualifiable.
This does not work with object methods, however; all object
methods have to be in the symbol table of some package to be found.
Just because the lexical variable is lexically (also called
statically) scoped doesn't mean that within a function it
works like a C static. It normally works more like a C auto.
But here's a mechanism for giving a function private variables
with both lexical scoping and a static lifetime. If you do want
to create something like C's static variables, just enclose the
whole function in an extra block, and put the static variable
outside the function but in the block.
{
my $secret_val = 0;
sub gimme_another {
return ++$secret_val;
}
}
# $secret_val now becomes unreachable by the outside
# world, but retains its value between calls to gimme_another
If this function is being sourced in from a separate file via
require or use, then this is probably just fine. If it's all
in the main program, you'll need to arrange for the my() to be
executed early, either by putting the whole block above your main
program, or more likely, placing merely a BEGIN sub around it to
make sure it gets executed before your program starts to run:
sub BEGIN {
my $secret_val = 0;
sub gimme_another {
return ++$secret_val;
}
}
See the perlrun manpage about the BEGIN function.
Temporary Values via local()
NOTE: In general, you should be using "my" instead of "local",
because it's faster and safer. Exceptions to this include the
global punctuation variables, filehandles and formats, and direct
manipulation of the Perl symbol table itself. Format variables
often use "local" though, as do other variables whose current
value must be visible to called subroutines.
Synopsis:
local $foo; # declare $foo dynamically local
local (@wid, %get); # declare list of variables local
local $foo = "flurp"; # declare $foo dynamic, and init it
local @oof = @bar; # declare @oof dynamic, and init it
local *FH; # localize $FH, @FH, %FH, &FH ...
local *merlyn = *randal; # now $merlyn is really $randal, plus
# @merlyn is really @randal, etc
local *merlyn = 'randal'; # SAME THING: promote 'randal' to *randal
local *merlyn = \$randal; # just alias $merlyn, not @merlyn etc
A local() modifies its listed variables to be local to the
enclosing block, (or subroutine, eval{}, or do) and any called from
within that block. A local() just gives temporary values to global
(meaning package) variables. This is known as dynamic scoping.
Lexical scoping is done with "my", which works more like C's
auto declarations.
If more than one variable is given to local(), they must be placed
in parentheses. All listed elements must be legal lvalues.
This operator works by saving the current values of those
variables in its argument list on a hidden stack and restoring
them upon exiting the block, subroutine, or eval. This means
that called subroutines can also reference the local variable,
but not the global one. The argument list may be assigned to if
desired, which allows you to initialize your local variables.
(If no initializer is given for a particular variable, it is
created with an undefined value.) Commonly this is used to name
the parameters to a subroutine. Examples:
for $i ( 0 .. 9 ) {
$digits{$i} = $i;
}
# assume this function uses global %digits hash
parse_num();
# now temporarily add to %digits hash
if ($base12) {
# (NOTE: not claiming this is efficient!)
local %digits = (%digits, 't' => 10, 'e' => 11);
parse_num(); # parse_num gets this new %digits!
}
# old %digits restored here
Because local() is a run-time command, it gets executed every
time through a loop. In releases of Perl previous to 5.0, this
used more stack storage each time until the loop was exited.
Perl now reclaims the space each time through, but it's still
more efficient to declare your variables outside the loop.
A local is simply a modifier on an lvalue expression. When you
assign to a localized variable, the local doesn't change whether
its list is viewed as a scalar or an array. So
local($foo) = <STDIN>;
local @FOO = <STDIN>;
both supply a list context to the right-hand side, while
local $foo = <STDIN>;
supplies a scalar context.
A note about local() and composite types is in order. Something
like local(%foo) works by temporarily placing a brand new hash
in the symbol table. The old hash is left alone, but is hidden
"behind" the new one.
This means the old variable is completely invisible via the
symbol table (i.e. the hash entry in the *foo typeglob) for the
duration of the dynamic scope within which the local() was seen.
This has the effect of allowing one to temporarily occlude any
magic on composite types. For instance, this will briefly alter
a tied hash to some other implementation:
tie %ahash, 'APackage';
[...]
{
local %ahash;
tie %ahash, 'BPackage';
[..called code will see %ahash tied to 'BPackage'..]
{
local %ahash;
[..%ahash is a normal (untied) hash here..]
}
}
[..%ahash back to its initial tied self again..]
As another example, a custom implementation of %ENV might look
like this:
{
local %ENV;
tie %ENV, 'MyOwnEnv';
[..do your own fancy %ENV manipulation here..]
}
[..normal %ENV behavior here..]
--tom, who can't believe anyone made it this far.
--
Tom Christiansen tchrist@jhereg.perl.com
With a PC, I always felt limited by the software available. On Unix, I am
limited by my knowledge. --Peter J. Schoenster <pschon@baste.magibox.net>
------------------------------
Date: Thu, 04 Dec 1997 20:13:21 GMT
From: faust@wwa.com (Faust Gertz)
Subject: Re: need the skinny on my() vs local()
Message-Id: <34880cb0.2411484@news.wwa.com>
On Thu, 4 Dec 1997 13:45:06 -0500, "Dave Kaufman"
<davidk@nospam.cnct.com> wrote:
>What is the difference between my() and local() ?
Have you ever read Paul De Man's _Allegories of Reading_? :-)
>I read the camel book explanation but it sailed right over my pea brain. It
>explained the difference in terms of lexical namespaces, assuming I knew
>what a lexical namespace was :-)
>
>Can someone lend me a clue?
I know a document or two that can.
>Will the world come tumbling down if I change
>those local's to my's?
Possibly.
>Will Hell freeze over?
Not until the Chicago Cubs win the World Series.
>Will Larry come down and thump me on the head?
No, but someone will write a script to do it for him.
>Or will all mankind learn to love one another and
>world peace be finally achieved?
Ok, enough. Here is what the FAQ
(http://www.perl.com/CPAN-local/doc/FAQs/FAQ/PerlFAQ.html#What_s_the_diference_betwen_dy)
has to say.
>What's the difference between dynamic and lexical (static) scoping?
>Between local() and my()?
>
>local saves away the old value of the global variable $x, and assigns a new value for the duration of the subroutine, which is
>visible in other functions called from that subroutine. This is done at run-time, so is called dynamic scoping. local always
>affects global variables, also called package variables or dynamic variables.
>
>my creates a new variable that is only visible in the current subroutine. This is done at compile-time, so is called lexical or static
>scoping. my always affects private variables, also called lexical variables or (improperly) static(ly scoped) variables.
>
>For instance:
>
> sub visible {
> print "var has value $var\n";
> }
>
> sub dynamic {
> local $var = 'local'; # new temporary value for the still-global
> visible(); # variable called $var
> }
>
> sub lexical {
> my $var = 'private'; # new private variable, $var
> visible(); # (invisible outside of sub scope)
> }
>
> $var = 'global';
>
> visible(); # prints global
> dynamic(); # prints local
> lexical(); # prints global
>
>Notice how at no point does the value ``private'' get printed. That's because $var only has that value within the block of the
>lexical function, and it is hidden from called subroutine.
>
>In summary, local doesn't make what you think of as private, local variables. It gives a global variable a temporary value. my is
>what you're looking for if you want private variables.
>
>See also the perlsub manpage (http://www.perl.com/CPAN-local/doc/manual/html/pod/perlsub.html), which explains this
>all in more detail.
Streben nach Wahrheit
Faust Gertz
Philosopher at Large
------------------------------
Date: Thu, 04 Dec 1997 13:38:00 -0500
From: fl_aggie@thepentagon.com (I R A Aggie)
Subject: Re: Perl4 is not Y2K (was Re: Forced to use brain-dead perl 4 -- how do I accomplish task that is simple in perl 5 ?)
Message-Id: <-0412971338000001@aggie.coaps.fsu.edu>
In article <EKMro4.Gp6@world.std.com>, aml@world.std.com (Andrew M.
Langmead) wrote:
+ Although I can't come up with a good reason why I prefer a phrase that
+ is intentionally misleading over one that is deliberately deceiptful.
Well, its too late now. The rumor mill will run with it, and blow it
completely out of proportion. Eventually, perl 4 will be blamed for
violence, flood, famine, and El Nino.
James
--
Consulting Minister for Consultants, DNRC
Support the anti-Spam amendment <url:http://www.cauce.org/>
To cure your perl CGI problems, please look at:
<url:http://www.perl.com/perl/faq/idiots-guide.html>
------------------------------
Date: 4 Dec 1997 19:06:24 GMT
From: mjtg@cus.cam.ac.uk (M.J.T. Guy)
Subject: Re: Perl4 is not Y2K (was Re: Forced to use brain-dead perl 4 -- how do I accomplish task that is simple in perl 5 ?)
Message-Id: <666uvg$bfb$1@lyra.csx.cam.ac.uk>
I R A Aggie <fl_aggie@thepentagon.com> wrote:
>
>Well, its too late now. The rumor mill will run with it, and blow it
>completely out of proportion. Eventually, perl 4 will be blamed for
>violence, flood, famine, and El Nino.
Not to mention the plague of Camel fleas.
Mike Guy
------------------------------
Date: 4 Dec 1997 19:01:23 GMT
From: mjtg@cus.cam.ac.uk (M.J.T. Guy)
Subject: Re: perlop clarification request
Message-Id: <666um3$b64$1@lyra.csx.cam.ac.uk>
Stuart Cooper <stuartc@ind.tansu.com.au> wrote:
>
> The comma operator comes from 'C'; where it has the same semantics.
>Two possible uses:
>
> 1) return a value of true for this statement regardless:
>
> $i_is_set = ($i=0, 1);
>
> almost certainly the left hand side (LHS) will be doing something useful;
>even though the programmer by using the comma operator disclaims interest in
>the return value. The LHS becomes a side-effect (which Lisp and
>other functional programmers are addicted to) of the statement. ie "return
>this; but sneak this in on the side". An example in the Blue Perl Book under
>the select (output filehandle) function is:
>
> select((select(STDERR), $| =1)[0])
But sadly, that isn't an example of the comma operator _in a scalar context_.
The typical use of comma in a scalar context is where you'd otherwise
write a semicolon, except that you want the result to be syntactically
an expression, such as
($done=1), last if $complete;
Usually, as in the above, you can rewrite it to use a semicolon, at the
expense of a little more line noise.
if ($complete) { $done=1; last };
Mike Guy
------------------------------
Date: Tue, 2 Dec 1997 16:57:17 -0800
From: Tom Phoenix <rootbeer@teleport.com>
To: Curtis Hrischuk <ceh@sunspot.sce.carleton.ca>
Subject: Re: problem with odd number of elements in hash table
Message-Id: <Pine.GSO.3.96.971202165540.19514W-100000@usertest.teleport.com>
On 2 Dec 1997, Curtis Hrischuk wrote:
> Odd number of elements in hash list at
> /home/ceh/ObjecTime/src/ObjectimeBridge.pm line 118 (#1)
What is line 118 of that module? If it's the line that you've quoted, I
wonder whether you're using a tied variable, or something like that. Good
luck!
--
Tom Phoenix http://www.teleport.com/~rootbeer/
rootbeer@teleport.com PGP Skribu al mi per Esperanto!
Randal Schwartz Case: http://www.rahul.net/jeffrey/ovs/
Ask me about Perl trainings!
------------------------------
Date: 4 Dec 1997 19:59:43 GMT
From: ilya@math.ohio-state.edu (Ilya Zakharevich)
Subject: Re: Q: lambda fun, loop, string to expr
Message-Id: <66723f$i1c$1@agate.berkeley.edu>
In article <3486e84d$3$ofn$mr2ice@speaker>,
Brandon S. Allbery KF8NH; to reply, change "void" to "kf8nh" <bsa@void.apk.net> wrote:
> | Quite the opposite, it is going ahead of the rest of Perl, where you cannot
> | call a chunk of code without an *enourmous* overhead.
> +--->8
>
> But you can't adapt that to Perl subs in general, since sort's BLOCK parameter
> is deliberately optimized to skip some context setup. Omit setting up the
> context for subs in general and an awful lot of subs are going to break
> horribly....
If this were true, you would not be able to put whatever you want
after `sort'.
However, it IS true - in *general*.
I *think* a lot of subroutines *will* survive a simplified call frame,
but somebody should code a "sniffer" for such subroutines and a
simplified "caller".
Ilya
------------------------------
Date: Thu, 04 Dec 1997 12:54:14 -0500
From: Eryq <eryq@zeegee.com>
To: Fabrizio Pivari <pivari@geocities.com>
Subject: Re: Q: multiline
Message-Id: <3486EE46.77B2@zeegee.com>
Fabrizio Pivari wrote:
>
> Hi,
>
> I have some problems to find a good method to match in multiline.
> For example I want to find the title of an HTML file.
> I use this method
> if(/<TITLE>/i .. /<\/TITLE>/i)
> {
> $Title.=$_;
> $Title=~/<TITLE>(.*)<\/TITLE>/i;
> $title=$1;
> }
>
> I think this isn't a good method.
> Can you help me?
I would suggest getting a copy of HTML::Parse from the CPAN.
It provides you with a real simple way to parse anything you
want out of an HTML document, reliably. Hope that helps,
--
___ _ _ _ _ ___ _ Eryq (eryq@zeegee.com)
/ _ \| '_| | | |/ _ ' / President, Zero G Inc.
| __/| | | |_| | |_| | "Talk is cheap. Let's build." - Red Green.
\___||_| \__, |\__, |___/\ Visit STREETWISE, Chicago's newspaper by/
|___/ |______/ of the homeless: http://www.streetwise.org
------------------------------
Date: Thu, 04 Dec 1997 19:39:14 GMT
From: faust@wwa.com (Faust Gertz)
Subject: Re: Recommended PERL-book?
Message-Id: <3487068a.837307@news.wwa.com>
On 4 Dec 1997 16:12:02 GMT, Tom Christiansen <tchrist@mox.perl.com>
wrote:
>In comp.lang.perl.misc, Gary Howland <ghowland@hotlava.com> writes:
>:> I want to find a book that describes the basics of PERL,
> ^^^^^^
>
>:"Advanced Perl Programming" is the best perl book by a long shot.
> ^^^^^^^^
>
>Huh?
Sure, it describes all the (advanced) basics of Perl. :-)
Streben nach Wahrheit
Fausrt Gertz
Philosopher at Large
------------------------------
Date: Thu, 4 Dec 1997 10:19:08 -0800
From: "Mark Imel" <mark@seattlelab.com>
Subject: Returning Values from a Perl script
Message-Id: <666sb4$ldo$1@usenet88.supernews.com>
Being a fairly new japh,
I'm not sure how to return a value (or address)
from my perl script, which was activated by the embedded perl interpreter
from my c program.
e.g.
CProgram ----->>>> embeded Perl Interpreter ---->>>> Perl script ---
|
return value <<<<<<<<<<<<<<<<<<<<<<<<<<< ----------------
Any ideas?
--mark
------------------------------
Date: 3 Dec 1997 02:02:54 GMT
From: "S. Lam" <Slammy@postoffice.worldnet.att.net>
Subject: Shell command in Perl
Message-Id: <662eke$qo0@bgtnsc03.worldnet.att.net>
I'm very unfamiliar with Perl and I am trying to make a shell command to
invoke Sendmail. I've included the header:
Use Shell qw(mail);
what I'm stuck on is the exact syntax on how to invoke the mailer. I've
trying to do the following:
mail someone@foo.bar < message.file
I know other shell commands require parenthesis and quotes, but l can't
figure out the syntax for this one. None of the books that I have show
anything on this.
any help would be greatly appreciated.
Sam
------------------------------
Date: Thu, 04 Dec 1997 02:03:43 GMT
From: dgrove@ntslink.net (David Grove)
Subject: Tk and Lwp under Activeware
Message-Id: <34860f4c.13737984@news.ntslink.net>
Is there a port of Tk to Activeware. I need 310 for the perl2exe
'compiler'. Also... same question for LWP.
------------------------------
Date: 4 Dec 1997 11:59:58 -0800
From: mcravit@best.com (Matthew Cravit)
Subject: Re: Tk and Lwp under Activeware
Message-Id: <66723u$1co$1@shell3.ba.best.com>
In article <34860f4c.13737984@news.ntslink.net>,
David Grove <dgrove@ntslink.net> wrote:
>Is there a port of Tk to Activeware. I need 310 for the perl2exe
>'compiler'. Also... same question for LWP.
Not for Activeware. However, the Win32 port of Perl by Gurusamy Sarathy (sp?)
is much better anyway (for example, it actually supports flock), and it
includes Tk, LWP, and a bunch of other useful modules. You can get it from
your local CPAN archive under authors/id/GSAR. For a list of CPAN sites,
go to http://www.perl.com/CPAN/SITES.html.
Hope this helps.
/MC
--
Matthew Cravit, N9VWG | Experience is what allows you to
E-mail: mcravit@best.com (home) | recognize a mistake the second
mcravit@taos.com (work) | time you make it.
------------------------------
Date: Thu, 4 Dec 1997 18:44:26 GMT
From: "Howell Caton (ISTD/TD) <caton>" <caton@arl.mil>
Subject: Using Pipe with Fork
Message-Id: <3486FA0A.D5E@arl.mil>
Greetings: I want to use pipe with fork to pipe data to and from the
same executable, but I don't know how to associate READHANDLE and
WRITEHANDLE with the executable. Do I use "open" like this?
open(READHANDLE, "doit|");
open(WRITEHANDLE, "|doit");
I don't think so! The idea solution would be for someone to point
me to an example where this is done. Thanks!
--
Howell Caton
Army Research Lab.
ATTN: AMSRL-IS-TP
Aberdeen Proving Ground, MD 21005
phone 410-278-8942
FAX 410-278-9223
caton@arl.mil
------------------------------
Date: 8 Mar 97 21:33:47 GMT (Last modified)
From: Perl-Request@ruby.oce.orst.edu (Perl-Users-Digest Admin)
Subject: Digest Administrivia (Last modified: 8 Mar 97)
Message-Id: <null>
Administrivia:
The Perl-Users Digest is a retransmission of the USENET newsgroup
comp.lang.perl.misc. For subscription or unsubscription requests, send
the single line:
subscribe perl-users
or:
unsubscribe perl-users
to almanac@ruby.oce.orst.edu.
To submit articles to comp.lang.perl.misc (and this Digest), send your
article to perl-users@ruby.oce.orst.edu.
To submit articles to comp.lang.perl.announce, send your article to
clpa@perl.com.
To request back copies (available for a week or so), send your request
to almanac@ruby.oce.orst.edu with the command "send perl-users x.y",
where x is the volume number and y is the issue number.
The Meta-FAQ, an article containing information about the FAQ, is
available by requesting "send perl-users meta-faq". The real FAQ, as it
appeared last in the newsgroup, can be retrieved with the request "send
perl-users FAQ". Due to their sizes, neither the Meta-FAQ nor the FAQ
are included in the digest.
The "mini-FAQ", which is an updated version of the Meta-FAQ, is
available by requesting "send perl-users mini-faq". It appears twice
weekly in the group, but is not distributed in the digest.
For other requests pertaining to the digest, send mail to
perl-users-request@ruby.oce.orst.edu. Do not waste your time or mine
sending perl questions to the -request address, I don't have time to
answer them even if I did know the answer.
------------------------------
End of Perl-Users Digest V8 Issue 1407
**************************************