[9875] in Perl-Users-Digest
Perl-Users Digest, Issue: 3467 Volume: 8
daemon@ATHENA.MIT.EDU (Perl-Users Digest)
Mon Aug 17 18:07:17 1998
Date: Mon, 17 Aug 98 15:00:25 -0700
From: Perl-Users Digest <Perl-Users-Request@ruby.OCE.ORST.EDU>
To: Perl-Users@ruby.OCE.ORST.EDU (Perl-Users Digest)
Perl-Users Digest Mon, 17 Aug 1998 Volume: 8 Number: 3467
Today's topics:
"use vars qw(var)" -vs- "my $var" <matta@geoworks.com>
Re: $POSTMATCH question <uri@sysarch.com>
Re: COBOL and Perl <sneaker@sneex.fccj.org>
Re: COBOL and Perl (John Moreno)
Re: Complex Regular Expression <jdf@pobox.com>
Re: Complex Regular Expression (Greg Bacon)
Re: Continuing misunderstanding of symbol table manipul (Greg Bacon)
Re: Converting to lowecase <grant.griffin@nospam.com>
Re: Converting to lowecase (Tad McClellan)
Converting to Uppercase to some Lower Case. <pan@part.net>
Re: Converting to Uppercase to some Lower Case. (Sean McAfee)
Re: Converting to Uppercase to some Lower Case. (Craig Berry)
Re: Converting to Uppercase to some Lower Case. (Greg Bacon)
Re: Dynamic scoping across closures? <jdf@pobox.com>
Re: Dynamic scoping across closures? <zenin@bawdycaste.org>
Re: Dynamic scoping across closures? (Greg Bacon)
Re: Error output problem. <sneaker@sneex.fccj.org>
File UPLOAD not working with NetScape <tbeaulieu@mediaone.net>
Re: filehandle in CGI.pm <tbeaulieu@mediaone.net>
Re: here's an implementation of diff in perl <scribble@pobox.com>
Re: here's an implementation of diff in perl <scribble@pobox.com>
Special: Digest Administrivia (Last modified: 12 Mar 98 (Perl-Users-Digest Admin)
----------------------------------------------------------------------
Date: Mon, 17 Aug 1998 14:41:49 -0700
From: Matt Armstrong <matta@geoworks.com>
Subject: "use vars qw(var)" -vs- "my $var"
Message-Id: <35D8A39D.33E4F7F8@geoworks.com>
What is the practical difference between "use vars qw(var)" and a "my
$var" at file scope?
What package are variables placed in with "use vars?" Are they always
place in 'main'? This seems reasonable, since the info docs say they
are "global variable names."
Can variables declared with "use vars" clash with other packages?
What does "use vars" actually do (I already know what the documentation
says -- namely that it'll make warnings go away -- I'd like to know why
they go away).
Traditionally, when using "use strict" and coming across situations
where code was looking for an explicit package name, I just called the
variables $main::whatever. How is "use vars" a superior solution?
Thanks for any insight!
------------------------------
Date: 17 Aug 1998 16:13:35 -0400
From: Uri Guttman <uri@sysarch.com>
To: "J.M. Cheng" <jachin.cheng@gsc.gte.com>
Subject: Re: $POSTMATCH question
Message-Id: <x7n2934b9s.fsf@sysarch.com>
>>>>> "JMC" == J M Cheng <*jachin.cheng@gsc.gte.com*> writes:
JMC> I'm trying to use the $POSTMATCH ($') function in a script that parses
JMC> JavaScripts out of HTML files. However, I am getting unexpected results
JMC> from the operator.
you definitely need to learn more perl and regex stuf in particular. i
will provide some comments and pointer that may help you on your way.
in general, the use $` and $' are deprecated as they slow down ALL
regexes in your code. read "mastering regular expressions" for more
about that (and all you ever wanted to know about regexes).
you can emulate them in most cases with ^(.+) and (.+)$ or some
variation on those.
all my comments are untested. a major dsign change would be to use the
range operator (..) to get the lines between the <script> and
</script>. study that operator
JMC> $line = <INFILE>;
JMC> while ($line ne ""){
more correctly and simpler is:
while (defined( $line = <INFILE> ) ) {
and use next in the body of the loop (see below)
JMC> # look for opening SCRIPT tag, ignore attributes
JMC> if ($line =~ / \< [\s]* SCRIPT [\s]* .* \> /gix){
use another regex delimiter so you won't have to backslash the slashes
< and > ned no quoting, \s (nor any single char) does not need to be in
a char class [],
if ($line =~ m|(.+)? < \s* SCRIPT \s* .* > |gix){
now you can use $1 instead of prematch
print OUTFILE ( "PREMATCH: $1\n";
JMC> # include anything in the line before the SCRIPT tag
JMC> $line = $`;
JMC> print OUTFILE ( "PREMATCH: ", $line, "\n");
JMC> print ( "PREMATCH: ", $line, "\n" );
JMC> # skip lines between SCRIPT tags
JMC> $line = <INFILE>;
JMC> while ($line !~ /\< [\s]* \/ [\s]* SCRIPT [\s]* \> /gix){
do the same while loop as above, then test.
JMC> print ("JavaScript LINE>>>", $line);
JMC> print OUTFILE ("JavaScript LINE>>>", $line);
JMC> $line = <INFILE>;
don't read line here, but in the while loop.
next ;
JMC> }
JMC> $line2 =~ /\< [\s]* \/ [\s]* SCRIPT [\s]* \> /gix;
here is your biggest bug, you have line2 and not line so it never
matches.
JMC> # include anything in the line after the SCRIPT tag
JMC> $line2 = $';
JMC> }
hth,
uri
--
Uri Guttman ----------------- SYStems ARCHitecture and Software Engineering
Perl Hacker for Hire ---------------------- Perl, Internet, UNIX Consulting
uri@sysarch.com ------------------------------------ http://www.sysarch.com
The Best Search Engine on the Net ------------- http://www.northernlight.com
------------------------------
Date: Mon, 17 Aug 1998 16:03:39 -0400
From: Bill 'Sneex' Jones <sneaker@sneex.fccj.org>
Subject: Re: COBOL and Perl
Message-Id: <35D88C9B.3B758F9D@sneex.fccj.org>
[Cobol group deleted.]
Jonathan Feinberg wrote:
>
> DavidM <dmcs@cyburban.com> writes:
>
> > Can you write CICS programs in PERL?
> > Can you write IMS programs in PERL?
>
> Hmm.
>
> --
> Jonathan Feinberg jdf@pobox.com Sunny Brooklyn, NY
> http://pobox.com/~jdf/
I will say that on S/390 running VM/CMS with the POSIX
extension you can :]
Yes, Perl was ported to VM/CMS; amazing huh?
(OK OK, it's still EBCIDIC.)
-Sneex- :]
__________________________________________________________________
Bill Jones | FCCJ Webmaster | Life is a 'Do it yourself' thing...
http://webmaster.fccj.org/cgi/mail?webmaster
------------------------------
Date: Mon, 17 Aug 1998 17:22:56 -0400
From: phenix@interpath.com (John Moreno)
Subject: Re: COBOL and Perl
Message-Id: <1ddwwjl.1l0qob11b0wdmaN@roxboro0-010.dyn.interpath.net>
In comp.lang.perl.misc DavidM <dmcs@cyburban.com> wrote:
> Abigail wrote:
-snip-
> > ++ Are there things in COBOL which can't be done in Perl.
> >
>
> Can you dynamically call subroutines in Perl?
> Can you do SORT's in PERL?
> Can PERL use different collating sequences?
> Can you write CICS programs in PERL?
> Can you write IMS programs in PERL?
This is stupid - as Abigail points out, both are turing complete
languages. What this means is that if one language can do it another
can too - the difference is in how easy it is to do so.
For instance, I just made a patch for a newsreader which will allow it
to trim references and to keep the total length under 999 (including
CRLF).
What took 30 lines of C code:
$references =~ s/.+?(<[^ <]+>)/$1 /sg;
$references =~ s/.+(<.{983}>)/$1/;
I did exactly the same thing in both languages, one was /much/ easier
than the other - but you can do the same thing in any turing complete
language (if you're desperate or crazy enough you can always do it by
including a compiler/interpreter written in the first language for the
second language and the program that you want done). That's what a
turing complete language means.
(for those of you who may be wondering - no that isn't the prefered way
to trim references, but it works and I think the preferred method has
more redundancy than is actually required [or good for it] in real world
use. Plus I was writing for a program I can't test [different platform]
and wanted to keep it simple.).
--
John Moreno
------------------------------
Date: 17 Aug 1998 16:16:51 -0500
From: Jonathan Feinberg <jdf@pobox.com>
To: Kevin Holbrook <kevin@templegames.com>
Subject: Re: Complex Regular Expression
Message-Id: <zpd3ux4s.fsf@mailhost.panix.com>
Kevin Holbrook <kevin@templegames.com> writes:
> Sorry for my ignorance here, but does anyone know the proper
> expression for matching a comma in the middle of a double-quoted
> alpha-numeric string?
What have you tried so far that hasn't worked?
--
Jonathan Feinberg jdf@pobox.com Sunny Brooklyn, NY
http://pobox.com/~jdf/
------------------------------
Date: 17 Aug 1998 20:58:36 GMT
From: gbacon@cs.uah.edu (Greg Bacon)
Subject: Re: Complex Regular Expression
Message-Id: <6ra5ht$39o$4@info.uah.edu>
In article <35D885B8.63ADFE91@templegames.com>,
Kevin Holbrook <kevin@templegames.com> writes:
: Sorry for my ignorance here, but does anyone know the proper expression
: for matching a comma in the middle of a double-quoted alpha-numeric
: string?
You didn't specifically state what sort of problem you're tackling, but
is it possible that
"How can I split a [character] delimited string except when inside
[character]? (Comma-separated files)"
from section four of the Perl FAQ might help?
Greg
--
If crime fighters fight crime, and firefighters fight fire, what do freedom
fighters fight? They never mention that part to us, do they?
-- George Carlin
------------------------------
Date: 17 Aug 1998 20:53:50 GMT
From: gbacon@cs.uah.edu (Greg Bacon)
Subject: Re: Continuing misunderstanding of symbol table manipulation (was Re: Have package use another symbol table?)
Message-Id: <6ra58u$39o$3@info.uah.edu>
In article <9EZB1.855$QT4.4232788@newbabylon.rs.itd.umich.edu>,
mcafee@choplifter.rs.itd.umich.edu (Sean McAfee) writes:
: $FOO::x = 10; # The typeglob $FOO::{x} now has the value "10"
: # hanging off it in the scalar slot
: %BAR:: = %FOO::; # Equivalent to $BAR::{x} = $FOO::{x}; the typeglob
: # $BAR::{x} should now have the value "10" in its scalar
: # slot, the *same* "10" that's in $FOO::{x}'s scalar slot.
: print $BAR::x; # Ought to print "10", but doesn't.
:
: Replacing "%BAR:: = %FOO::" with "$BAR::{x} = $FOO::{x}" produces the
: results I expect. Why aren't the two identical, presuming that package
: FOO's symbol table contains only the typeglob "x"?
That's very odd. Consider this program:
#! /usr/bin/perl -w
use strict;
$FOO::x = 10;
$BAR::x = 20;
%BAR:: = %FOO::;
print "\$FOO::x = $FOO::x\n";
print "\$BAR::x = $BAR::x\n";
When run from the command line, I get this output
$FOO::x = 10
$BAR::x = 20
However, when I run it in the debugger, this happens:
main::(try:5): $FOO::x = 10;
DB<1> c
$FOO::x = 10
$BAR::x = 20
Debugged program terminated. Use q to quit or R to restart,
use O inhibit_exit to avoid stopping after program termination,
h q, h R or h O to get additional info.
DB<1> V FOO
$x = 10
DB<2> V BAR
$x = 10
DB<3> p *FOO::x{SCALAR}
SCALAR(0x10106f38)
DB<4> p *BAR::x{SCALAR}
SCALAR(0x10106f38)
Apparently, it's working as you (and I) would expect in the debugger.
A bug?
Greg
--
I feel like a God-damned mushroom - kept in the dark and fed bullshit!
-- Impulse
------------------------------
Date: Mon, 17 Aug 1998 14:30:44 -0500
From: Grant Griffin <grant.griffin@nospam.com>
To: Craig Berry <cberry@cinenet.net>
Subject: Re: Converting to lowecase
Message-Id: <35D884E4.5620E86B@nospam.com>
> Bzzzzt, category error! Not hostile to newbies; welcoming, friendly, and
> supportive to newbies. Hostile to people who ask questions easily
> answered by consulting FAQs/docs. That's a huge difference.
>
> : If someone ask a question that is in the experts eye pretty basic,
> : instead of offering a tip or solution the poor newbie is slagged of and
> : told to read the manuals (like if he had not tried this allready).
>
> Which you clearly didn't, making you worthy of slagging. I have *never*
> *once* seen a poster who had clearly made a good-faith attempt to use the
> docs get flamed. *NEVER* *ONCE*. It doesn't happen. So your arguments
> are entirely missing the point.
There once was a park which was beautiful when first created, but which began to be
littered by people who were too lazy to throw away their own trash. So a small
group of well intended Citizens who wanted the park to be clean again decided to
take action, and they began confronting anybody they caught littering. To them, it
was a sort of "tough love". However, a few of these Citizens got carried away and
started really beating up anybody who littered. So now, most of the good decent
folks in the neighborhood--even those who used to pick up litter--stay away from
the park for fear that they might get beat up, or because they don't like
witnessing the beatings. But at least now the park is a better place.
=aesop2
------------------------------
Date: Mon, 17 Aug 1998 15:46:13 -0500
From: tadmc@metronet.com (Tad McClellan)
Subject: Re: Converting to lowecase
Message-Id: <lq4ar6.lau.ln@metronet.com>
Hauk Langlo (hauk@forumnett.no) wrote:
: Craig Berry wrote:
: > The *very first line matching the string 'lowercase' gives you your
: > answer! Now, wouldn't that have been easier to do, rather than waiting
: > for an answer from Usenet, and bothering thousands of people?
: You are ofcourse right about that. The problem has been though that due to
: some problems with my software, the server I'm using etc, I have not been
: able to use the perl man and docs lately.
When the server goes back up, copy all of the docs to your
local machine (or get a distribution and just suck out the docs).
They are just too valuable to do without. As you now know,
you could have had the answer in about 3-5 seconds if you had them.
*That's* productivity! ;-)
: Besides, I find it kind of strange
: that this board seem pretty hostile to newbies in general.
Many of the newbies seem to have that misconception, though it is
easy to see why.
There are "newbies" in several different areas (new to programming,
perl, CGI, or even newbies to Usenet itself).
Most often, it is 3-4 of those simultaneously that really get
the flame throwers on HI.
I don't think this newsgroup (it is not a "board" as in BBS, it is
a newsgroup, as in Usenet) is hostile to newbies who are having
problems with perl or even with programming in general.
It is hostile to people who:
----------
Post a Question that has been Asked Frequently in the past.
(Many man-hours spent on collecting answers validated by
*hundreds* of sets of eyes, wasted. Makes folks mad.
)
Post a question easily answered by 60-120 seconds of word
searching in the docs that *come with* perl.
(Many man-hours spent on carefully documenting how perl is
to behave, also validated by *hundreds* of sets of eyes, wasted.
Makes folks mad.
)
----------
Post a question that is not about perl or Perl.
(This is most often a misplaced CGI question. Even a newbie
can follow the links given in the Perl FAQ, part 9 to
help decide which newsgroup is most likely to yeild
answer paydirt...
Annoyance at off-topic postings is common in most newsgroups.
Nothing perl-specific about that one, see the FAQs posted
in the news.announce.newusers newsgroup.
)
----------
Demand an answer, or mark as Urgent.
(Volunteers are unconcerned with your anxiousness.
Consultants/contractors are much more responsive to
such concerns.
Also not a perl-specific annoyance on Usenet.
)
----------
Ask for an answer by email because they don't read the newsgroup.
(Like sneaking into a Wedding reception and hoping nobody knows
that you don't know bride nor groom.
Even that would be OK, but most here want to help as many
people as possible. Emailed answers benefit only one person.
Posted answers are open for all to see. (and the clever
newbie (and experienced hacker, for that matter) can get
their answer in seconds from on of the Usenet archives,
eg. www.dejanews.com
Once again, common to all of Usenet, not just this newsgroup.
).
If you read this newsgroup, then you know that it has a whole bunch
of traffic (If not, then don't say so ;-).
It seems to me that more than half of all posts are
time-wasters, as listed above.
(That's 50-100 "time wasters" each and every day.
Some folks have been reading the newsgroup for years!
Every thousand or so of those triggers a venting.
Unfortunate if your post happens to be the thousandth one ;-)
)
How do you think the folks who answer a lot of questions find your
question to answer? They read lots of articles!
Hence, they waste a lot of time (there are also Frequently Used Keywords
that many use to automatically discard the Silly Questions, it pays
to put a _little_ bit of thought into composing your Subject: header)
: If someone ask a
: question that is in the experts eye pretty basic, instead of offering a tip
: or solution the poor newbie is slagged of and told to read the manuals (like
: if he had not tried this allready).
Exactly.
If a keyword search would find it in under two minutes, then we
deduce that the did *not* try the docs first.
Given the large number of "keyword search" answerable questions posted
here every day, I think many haven't "tried this allready" (sic).
: I remember the friendly enviroment there used to be on similar Amiga
: programing boards some years ago. There people would help eachother out no
: matter what kind of stupid questions was asked.
BBSes and Usenet newsgroups are not the same thing.
Or did you mean on an Amiga newsgroup?
Also consider that the experienced ones here are the *nice* ones.
Who else would put up with seeing the same 2 dozen questions tens or
hundreds of times, *and keep on reading the newsgroup* ?
The easily bored ones have already wasted enough time on
Silly Questions, and no longer even read the newsgroup.
( Given the high correlation between eccentricities, such as being
easily disgusted with rote repetition, and high intelligence,
the most valuable of all Perl experts have likely already been
driven away from the newsgroup. (no slight to the "hardy" ones
reading this post ;-)
Let's do our small part to not drive away the few remaining ones.
)
: If this board are supposed to
: be for proffesional programmers only, then it should be clearly stated
: somewhere.
It is not for professional programmers only.
But, given the 'comp.lang' in the name, folks are expected to have
some small degree of technical savvy.
Like being able to read ;-)
And at least finding out the rules of a foreign society (that's right,
Usenet has its own little set of "rules", mentioned in the above
newsgroup) lest they execute a faux pas while attempting to solicit
a favor (answer).
: And I'm apologizing to the tousands of people i have bothered with my
: question.
Now there is a normal, well-socialized response to finding out that
you made a social blunder. You have character.
Much better than the usual newbie response of "screw the rules,
gimme my answer"...
You are hereby declared "reformed" ;-)
Use the docs and be a perl "insider"!
--
Tad McClellan SGML Consulting
tadmc@metronet.com Perl programming
Fort Worth, Texas
------------------------------
Date: Mon, 17 Aug 1998 15:05:40 -0600
From: "Eric Pan" <pan@part.net>
Subject: Converting to Uppercase to some Lower Case.
Message-Id: <903388079.157935@gate.part.net>
I need to convert title of all my books from upper case to normal title
sentences.
For example, What is the easiest way to convert from
IT'S EASY TO CONVERT
to
It's Easy to Convert.
Thanks.
--
-- Eric Pan
------------------------------
Date: Mon, 17 Aug 1998 21:29:57 GMT
From: mcafee@seawolf.rs.itd.umich.edu (Sean McAfee)
Subject: Re: Converting to Uppercase to some Lower Case.
Message-Id: <ph1C1.876$QT4.4390282@newbabylon.rs.itd.umich.edu>
In article <903388079.157935@gate.part.net>, Eric Pan <pan@part.net> wrote:
>I need to convert title of all my books from upper case to normal title
>sentences.
>For example, What is the easiest way to convert from
>IT'S EASY TO CONVERT
>to
>It's Easy to Convert.
You want to look at the \L, \l, \U, and \u string escapes, which are also
accessible via the lc, lcfirst, uc, and ucfirst functions, respectively.
To convert all of the words in a string to all-lowercase-except-for-the-
first-letter, something like this will suffice:
$title =~ s/(\S+)/\u\L$1/g;
If you have a set of words that should always be all lowercase, one
approach would be to store them in a list:
@all_lower = qw/ a an the to /;
$all_lower = join("|", @all_lower);
...then apply another substitution after the one given above:
$title =~ s/\b($all_lower)\b/\l$1/igo;
Making sure that the first word is always capitalized is left as an
exercise for the reader.
--
Sean McAfee | GS d->-- s+++: a26 C++ US+++$ P+++ L++ E- W+ N++ |
| K w--- O? M V-- PS+ PE Y+ PGP?>++ t+() 5++ X+ R+ | mcafee@
| tv+ b++ DI++ D+ G e++>++++ h- r y+>++** | umich.edu
------------------------------
Date: 17 Aug 1998 21:49:43 GMT
From: cberry@cinenet.net (Craig Berry)
Subject: Re: Converting to Uppercase to some Lower Case.
Message-Id: <6ra8hn$mec$1@marina.cinenet.net>
Eric Pan (pan@part.net) wrote:
: I need to convert title of all my books from upper case to normal title
: sentences.
:
: For example, What is the easiest way to convert from
:
: IT'S EASY TO CONVERT
:
: to
:
: It's Easy to Convert.
The tricky part is specifying what words to leave all lowercase (like 'to'
in your example. Here's my cut at it:
#!/usr/bin/perl -w
# titlecase - converts string to book-title case conventions.
# Craig Berry (980817)
use strict;
sub titlecase {
my @src = split ' ', lc shift; # Downcase, split on whitespace
my @dst = ucfirst shift @src; # Always init-cap first word
# List the words to exclude from init-capping. Extend to taste.
# Turn them into a hash for easy lookup.
my @exclude = qw( the in of a on as to );
my %excmap;
@excmap{@exclude} = (1) x @exclude;
# Init-cap each word not in the exclusion map, leave others alone.
push @dst, map { exists $excmap{$_} ? $_ : ucfirst $_ } @src;
# Put the words back together as a string and return it.
return join ' ', @dst;
}
chomp, print "$_ => ", titlecase($_), "\n" while <DATA>;
__DATA__
UlySSes
GONE WITH THE wIND
IT'S EASY TO CONVERT
a PortrAIT of the ARTIST AS A young man
learn PERL in 261 dAys
Which outputs:
UlySSes => Ulysses
GONE WITH THE wIND => Gone With the Wind
IT'S EASY TO CONVERT => It's Easy to Convert
a PortrAIT of the ARTIST AS A young man => A Portrait of the Artist as a Young Man
learn PERL in 261 dAys => Learn Perl in 261 Days
Hope this helps!
---------------------------------------------------------------------
| Craig Berry - cberry@cinenet.net
--*-- Home Page: http://www.cinenet.net/users/cberry/home.html
| Member of The HTML Writers Guild: http://www.hwg.org/
"Every man and every woman is a star."
------------------------------
Date: 17 Aug 1998 21:54:00 GMT
From: gbacon@cs.uah.edu (Greg Bacon)
Subject: Re: Converting to Uppercase to some Lower Case.
Message-Id: <6ra8po$39o$7@info.uah.edu>
In article <903388079.157935@gate.part.net>,
"Eric Pan" <pan@part.net> writes:
: I need to convert title of all my books from upper case to normal title
: sentences.
my %exception;
@exception{ qw( a an the of to ) } = ();
my $first = 1;
my $title = "IT'S EASY TO CONVERT";
my $new = join " ",
map {
if ($first) {
$first = 0;
"\u\L$_";
}
else {
my $lc = lc;
if (exists $exception{$lc}) {
$lc;
}
else {
"\u$lc";
}
}
} split ' ', $title;
You'll want to complete the list of exceptions as I can't remember
them all right now. :-)
Hope this helps,
Greg
--
A little poison now and then: that makes for pleasant dreams. And
much poison at the end for a pleasant death.
-- Nietzsche
------------------------------
Date: 17 Aug 1998 17:00:13 -0500
From: Jonathan Feinberg <jdf@pobox.com>
To: tbhudso@panther.cs.sandia.gov (Tramm Hudson)
Subject: Re: Dynamic scoping across closures?
Message-Id: <ww87uv4i.fsf@mailhost.panix.com>
tbhudso@panther.cs.sandia.gov (Tramm Hudson) writes:
> So if I call a closure that was created in another package, it's
> namespace will still be that of the other package and it won't see
> the "local" variables created in this package, right?
Right, unless it fully qualifies those variable names with the
package.
> Doesn't this contradict the intent of dynamic scoping?
local() saves the value of a global variable. Each global variable is
associated with a package. I don't see how this relates to the
concept of closures. There's no reason why you can't access a
package-qualified global from anywhere, including a closure. Here's
an example:
package Foo;
sub get_closure {
return sub { print "Your \$x is $main::x.\n"; };
}
package main;
local $x = 5;
my $c = Foo::get_closure();
$c->();
But why would you want to do this?
> Is there anyway to easily access the dynamic variables of the
> calling routine in a closure without requiring the closure to fully
> specify the package from which it wants to lookup the symbols?
Is there a reason you can't pass your dynamic variables (or anything,
for that matter) as parameters to the closure?
package Foo;
sub get_closure {
return sub {
my $param = shift;
print qq(You passed me "$param".\n);
};
}
package main;
local $x = 5;
my $c = Foo::get_closure();
$c->($x);
If you need the closure to change the value of variables in your
package, then pass references.
package Foo;
sub get_closure {
return sub {
my $ref = shift;
$$ref++;
};
}
package main;
local $x = 0;
my $c = Foo::get_closure();
$c->(\$x);
print "$x\n";
{
local $x = 50;
$c->(\$x);
print "$x\n";
}
print "$x\n";
I hope this helps!
--
Jonathan Feinberg jdf@pobox.com Sunny Brooklyn, NY
http://pobox.com/~jdf/
------------------------------
Date: 17 Aug 1998 21:13:44 GMT
From: Zenin <zenin@bawdycaste.org>
Subject: Re: Dynamic scoping across closures?
Message-Id: <903389058.216337@thrush.omix.com>
[posted & mailed]
Tramm Hudson <tbhudso@panther.cs.sandia.gov> wrote:
: So if I call a closure that was created in another package, it's
: namespace will still be that of the other package and it won't see
: the "local" variables created in this package, right?
Sure it will, just qualify them or do everything in one package.
: Doesn't this contradict the intent of dynamic scoping?
The intent of dynamic scoping is job security. Make code as
hard to maintain, expand, and reuse as possible so that
programmers everywere will be insured a safe future.
I don't see how this contradicts this intent. :-)
: We're roundabout getting to my question now. Is there anyway to
: easily access the dynamic variables of the calling routine in a closure
: without requiring the closure to fully specify the package from which
: it wants to lookup the symbols?
Yes. Have both the closure and the caller be in the same package.
Or, see below if you must do this...
: Or, in other words, to have the
: closure see the dynamically scoped variables as we would expect
: dynamically scoped variables to work?
Only punctuation variables ($@, $_, etc) are truly global in perl.
Nothing else is, nothing. You can access "globals" from anywhere,
via the full package name, or you can play aliasing and soft
reference games.
If you really, truly want to do this you can however. -This IS Perl
after all. The answer is soft references:
sub foo {
return sub {
my $pkg = caller();
print ${"${pkg}::foobar"};
};
}
But I warn you, down this path lies madness...
--
-Zenin (zenin@archive.rhps.org) From The Blue Camel we learn:
BSD: A psychoactive drug, popular in the 80s, probably developed at UC
Berkeley or thereabouts. Similar in many ways to the prescription-only
medication called "System V", but infinitely more useful. (Or, at least,
more fun.) The full chemical name is "Berkeley Standard Distribution".
------------------------------
Date: 17 Aug 1998 21:18:44 GMT
From: gbacon@cs.uah.edu (Greg Bacon)
Subject: Re: Dynamic scoping across closures?
Message-Id: <6ra6nk$39o$5@info.uah.edu>
In article <6ra0rs$e5$1@panther.cs.sandia.gov>,
tbhudso@panther.cs.sandia.gov (Tramm Hudson) writes:
: So if I call a closure that was created in another package, it's
: namespace will still be that of the other package and it won't see
: the "local" variables created in this package, right? Doesn't
: this contradict the intent of dynamic scoping?
I wouldn't say so. Think of C<package> as a way of telling perl
`pssst! The magic prefix is now Bletch.' Localized values are
still global, and anyone can still get at them. C<package> just
lets you partition your namespace nicely.
: We're roundabout getting to my question now. Is there anyway to
: easily access the dynamic variables of the calling routine in a closure
: without requiring the closure to fully specify the package from which
: it wants to lookup the symbols? Or, in other words, to have the
: closure see the dynamically scoped variables as we would expect
: dynamically scoped variables to work?
Hmm.. either you're in the minority with respect to how you expect
C<package> to behave or you just don't understand its semantics. The
semantics are really very simple: when perl encounters an unqualified
name, it silently qualifies it using the magic prefix that we
discussed before unless there is a lexical in scope, in which case
it uses that lexical whose name cannot be fully qualified.
Here's a puzzle originally proposed by tchrist (AFAIK). Given a
scope in which both a lexical and a dynamic with the same name
are present, how do you get at the value of each?
I see a few solutions to your problem:
1. Bite the bullet and fully qualify your variable.
sub gen_closure {
my $super_secret_value = rand;
sub {
no strict 'refs';
my($pkg) = caller;
$super_secret_value + ${ $pkg . "::" . "value" };
};
}
2. Pass a typeglob:
sub gen_closure {
my $super_secret_value = rand;
sub {
local *value = shift;
my($pkg) = caller;
$super_secret_value + $value;
};
}
$value = 42; ## must not be lexical!
my $closure = gen_closure;
$closure->(*value);
3. Pass a reference:
sub gen_closure {
my $super_secret_value = rand;
sub {
my $var = shift;
my($pkg) = caller;
$super_secret_value + $$var;
};
}
$value = 42;
my $closure = gen_closure;
$closure->(\$value);
I would use the third because you can get at both lexicals and dynamics
through a reference, but not through a typeglob or soft reference.
Hope this helps,
Greg
--
A meeting is an event at which the minutes are kept and the hours are lost.
------------------------------
Date: Mon, 17 Aug 1998 16:47:11 -0400
From: Bill 'Sneex' Jones <sneaker@sneex.fccj.org>
Subject: Re: Error output problem.
Message-Id: <35D896CF.9AE82771@sneex.fccj.org>
Jason Murray wrote:
>
> I am writing a script to log in to a list of machines on my network and
> execute a command. Some machines are a diffrent flavor of unix and
> fail. When the command succeds I use:
>
> $results = `rsh $machine <command>` and get the results in the variable
> $results.
>
> When the command fails I don't get the error in $results. Can anyone
> tell me how I can get the error. So I can rexecute the command with
> diffrent options.
>
> Thanks,
> jason
Are telnetting like this:
#!/usr/bin/perl -w
use strict;
use diagnostics;
use Net::Telnet ();
my $t = new Net::Telnet (Timeout => 2,
Errmode => 'return',
Prompt => '/bash\$ $/');
# ......
# This portion of code snipped to protect my network...
# ......
$hostNumber++;
$testTelnet = $domainNumber . $netWork . "." . $hostNumber;
$t->open("$testTelnet");
$msg = $t->errmsg;
print $ctr++, "\r";
print "\nMaybe \@ $testTelnet\n\n" unless $msg;
}
Or did you come with your own telnet? if so, then
you will have to figure out how to capture the error;
if you did something like the above - then these lines
will point you in the right direction:
$t->open("$testTelnet");
$msg = $t->errmsg;
print $ctr++, "\r";
print "\nMaybe \@ $testTelnet\n\n" unless $msg;
You will need to install the Net::Telnet module available
from your local CPAN.
HTH,
-Sneex- :]
__________________________________________________________________
Bill Jones | FCCJ Webmaster | Life is a 'Do it yourself' thing...
http://webmaster.fccj.org/cgi/mail?webmaster
------------------------------
Date: Mon, 17 Aug 1998 17:36:05 -0400
From: "Todd B" <tbeaulieu@mediaone.net>
Subject: File UPLOAD not working with NetScape
Message-Id: <6ra7qr$o4a$1@wbnws01.ne.highway1.com>
i need to process a binary file from a form upload. i am using code from
"the official guide to cgi.pm", and it works perfectly when the browser is
ie 4, but i get 0-bytyes read when the browser is netscape.
the content-type comes accross correctly. it opens correctly. attempting
to read from it produces no data, though.
any ideas?
------------------------------
Date: Mon, 17 Aug 1998 17:30:55 -0400
From: "Todd B" <tbeaulieu@mediaone.net>
Subject: Re: filehandle in CGI.pm
Message-Id: <6ra7h5$nrq$1@wbnws01.ne.highway1.com>
i suspect you may be using netscape 4.x. i am getting the same result. it
works with ie4, though. have not found out why this happens, but i am
experimenting with File::Copy in the meanwhile.
------------------------------
Date: 17 Aug 1998 16:10:18 -0500
From: Tushar Samant <scribble@pobox.com>
Subject: Re: here's an implementation of diff in perl
Message-Id: <6ra67q$50i@tekka.wwa.com>
mjd@plover.com writes:
>Tushar Samant <scribble@pobox.com> wrote:
>
>>Then one way to implement a "quality" parameter would be to consider
>>k lines as a "line". Cuts the time by k**2,
>
>Could be. Of course, you've also increased the time to compare two
>`lines' by a factor of k.
D'OH!
That pretty much kills THAT idea.
>I suppose you're planning to start out with k large and then make it
>smaller to re-examine the `lines' that are found to be different.
[...]
No. Let me try to remember just what I was thinking while half-
asleep. I was not thinking about making diff faster -- optimal
diff is equivalent to longest-common-subsequence and that's
obviously been studied quite well, and no half-assed armchair
theorizing is going to improve that.
Rather, I was trying to come up with a scheme with which you could
trade off time for SHORTER common subsequences, so that one extreme
would give you the optimal diff, and the other extreme would say
delete everything from file 1 and insert everything from file 2
(i.e. declaring that the common subsequence is null).
Since the latter case DOES happen when you just compare the files
(all the lines at once) and output your bloated diff iff they are
different, I thought taking a bigger or smaller chunk size would
lead to the desired trade-off. I was wrong.
Re-examining the chunks is another tangent altogether. The idea
was just to throw in several coordinates, and hoping that some
combination will give rise to a "quality" setting.
>But don't let me discourage you; I'd be interested to see what comes
>of it.
You mean actually *implementing*, etc? Ugh, how gross... I am a
DESIGNER.
------------------------------
Date: 17 Aug 1998 16:33:43 -0500
From: Tushar Samant <scribble@pobox.com>
Subject: Re: here's an implementation of diff in perl
Message-Id: <6ra7jn$65e@tekka.wwa.com>
abigail@fnx.com writes:
>Ilya Zakharevich (ilya@math.ohio-state.edu) wrote on MDCCCX September
>MCMXCIII in <URL: news:6r4lus$2as$1@mathserv.mps.ohio-state.edu>:
>++
>++ Sure not. Time to compare strings depends logarithmically on the
>++ length (if strings are randomly distributed, obviously this should be
>++ modified if there are common prefixes).
>
>Eh? If the time is sublinear, there must be characters not involved
>in the comparison. And if those characters are not involved - you
>don't know whether they are different.
True. Perhaps the desired "quality" setting might come from some
notion of approximate equality. For instance, two long strings
are equal if they are less than length 100 and equal, else we
pessimistically declare them unequal... This makes the
"comparison" constant time...
Armchair idea #2: don't redefine what your "lines" are, but
split up the files into chunks and concatenate optimal diffs on
corresponding pairs of chunks. Which brings the time down from
(m1 + ... + m10) * (n1 + ... + n10) to (m1*n1 + ... + m10*n10),
same constants. Also this gives some play in choosing the points
where you restart "zero-based" -- e.g. at the next "sub foo {"
line or after 60 lines whichever is earlier... yadda yadda yadda
HOWEVER! This is getting too metaphysical and I don't know what
it's going to accomplish anyway. My "idea" was, if you knew that
e.g. you had changed a file only on sparse isolated lines, you
should be able to say "use this much faster diff instead". But
how slow IS diff?
------------------------------
Date: 12 Jul 98 21:33:47 GMT (Last modified)
From: Perl-Request@ruby.oce.orst.edu (Perl-Users-Digest Admin)
Subject: Special: Digest Administrivia (Last modified: 12 Mar 98)
Message-Id: <null>
Administrivia:
Special notice: in a few days, the new group comp.lang.perl.moderated
should be formed. I would rather not support two different groups, and I
know of no other plans to create a digested moderated group. This leaves
me with two options: 1) keep on with this group 2) change to the
moderated one.
If you have opinions on this, send them to
perl-users-request@ruby.oce.orst.edu.
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 3467
**************************************