[18177] in Perl-Users-Digest

home help back first fref pref prev next nref lref last post

Perl-Users Digest, Issue: 345 Volume: 10

daemon@ATHENA.MIT.EDU (Perl-Users Digest)
Fri Feb 23 18:06:42 2001

Date: Fri, 23 Feb 2001 15:05:12 -0800 (PST)
From: Perl-Users Digest <Perl-Users-Request@ruby.OCE.ORST.EDU>
To: Perl-Users@ruby.OCE.ORST.EDU (Perl-Users Digest)
Message-Id: <982969512-v10-i345@ruby.oce.orst.edu>
Content-Type: text

Perl-Users Digest           Fri, 23 Feb 2001     Volume: 10 Number: 345

Today's topics:
        Basic: Arrays, shift, and the mystery element <djberge@uswest.com>
    Re: Basic: Arrays, shift, and the mystery element <mbudash@sonic.net>
    Re: Basic: Arrays, shift, and the mystery element <djberge@uswest.com>
    Re: Basic: Arrays, shift, and the mystery element (Rollin Thomas)
    Re: Difficult Split Question <bertilow@chello.se>
    Re: Difficult Split Question <joe+usenet@sunstarsys.com>
    Re: Difficult Split Question <godzilla@stomp.stomp.tokyo>
    Re: Difficult Split Question <godzilla@stomp.stomp.tokyo>
    Re: FAQ 4.61:   How do I reset an each() operation part (Rudolf Polzer)
    Re: FAQ 4.61:   How do I reset an each() operation part <uri@sysarch.com>
        flushing stdout (Erland Nylend)
    Re: help with variables in my email <Jonathan.L.Ericson@jpl.nasa.gov>
        HTML in a Perl Script <blankrr@mars-systems.com>
    Re: HTML in a Perl Script <shanem@ll.mit.edu>
        Is there a perl history equivalent? (BUCK NAKED1)
    Re: jeopardy posting <b_nospam_ill.kemp@wire2.com>
        max value in list? <prlawrence@lehigh.edu>
    Re: newbie question <laclac@global2000.net>
    Re: Perl in UNIX (Rudolf Polzer)
    Re: Perl in UNIX <mischief@velma.motion.net>
        Perl, Perl, Perl, don't give your love to URL (David Wall)
        Problem: Perl cgi calling Excel via OLE on Win2000 (Dave Fisher)
        question on how to code a program (Torque)
    Re: question on how to code a program (Peter L. Berghold)
    Re: Reading from __DATA__ (Rudolf Polzer)
    Re: server question (Logan Shaw)
        Sockets and bytecode <john_simpson@us.ibm.com>
        stock trading <vincentg@datashaping.com>
        Digest Administrivia (Last modified: 16 Sep 99) (Perl-Users-Digest Admin)

----------------------------------------------------------------------

Date: Fri, 23 Feb 2001 14:54:09 -0600
From: Daniel Berger <djberge@uswest.com>
Subject: Basic: Arrays, shift, and the mystery element
Message-Id: <3A96CDF1.DC19D4A@uswest.com>

Hi all,

Apparently I was asleep in Perl 101 when they covered this
topic.

I have a reference to an array of hash references.  I want to
continually shift that array based on a regex.  I'm getting
some rather unexpected results:

#!/usr/bin/perl -w

$hash1 = { name=>"Dan", gender=>"Male" };
$hash2 = { name=>"Ginger", gender=>"Female" };

my $arrayref = [$hash1, $hash2];

while($arrayref->[0]->{name} =~ /dan|ginger/i){
   print "\nBefore shift: ", scalar(@$arrayref), " record(s)";
   shift @$arrayref;
   print "\nAfter shift: ", scalar(@$arrayref), " records\n";
}

print "\n\nOutside of the loop, there are now: ",
scalar(@$arrayref), " records";

You will see that in the last iteration, the length of the array
is 0, yet it prints "1" outside of the loop.  What is happening?

If I try to print that element to see what it is:

print "\nElement is: ", @$arrayref;

This prints "HASH(0x8127284)".

Ok, so a hash reference is still on the array.  So let's
dereference and see what it is:

print "\nMystery name is: ", $arrayref->[0]->{name}

Nothing.

So, what exactly is happening here?

Thanks in advance for any help.

Regards,

Daniel Berger



------------------------------

Date: Fri, 23 Feb 2001 13:08:06 -0800
From: Michael Budash <mbudash@sonic.net>
Subject: Re: Basic: Arrays, shift, and the mystery element
Message-Id: <mbudash-83844A.13080623022001@news.pacbell.net>

In article <3A96CDF1.DC19D4A@uswest.com>, Daniel Berger 
<djberge@uswest.com> wrote:

> Hi all,
> 
> Apparently I was asleep in Perl 101 when they covered this
> topic.
> 
> I have a reference to an array of hash references.  I want to
> continually shift that array based on a regex.  I'm getting
> some rather unexpected results:
> 
> #!/usr/bin/perl -w
> 
> $hash1 = { name=>"Dan", gender=>"Male" };
> $hash2 = { name=>"Ginger", gender=>"Female" };
> 
> my $arrayref = [$hash1, $hash2];
> 
> while($arrayref->[0]->{name} =~ /dan|ginger/i){
>    print "\nBefore shift: ", scalar(@$arrayref), " record(s)";
>    shift @$arrayref;
>    print "\nAfter shift: ", scalar(@$arrayref), " records\n";
> }
> 
> print "\n\nOutside of the loop, there are now: ",
> scalar(@$arrayref), " records";
> 
> You will see that in the last iteration, the length of the array
> is 0, yet it prints "1" outside of the loop.  What is happening?

change:

while($arrayref->[0]->{name} =~ /dan|ginger/i){

to:

while ( defined($arrayref->[0]) && 
        $arrayref->[0]->{name} =~ /dan|ginger/i ) {

hth-
-- 
Michael Budash ~~~~~~~~~~ mbudash@sonic.net


------------------------------

Date: Fri, 23 Feb 2001 15:18:58 -0600
From: Daniel Berger <djberge@uswest.com>
Subject: Re: Basic: Arrays, shift, and the mystery element
Message-Id: <3A96D3C2.F5471EF8@uswest.com>

Michael Budash wrote:

> In article <3A96CDF1.DC19D4A@uswest.com>, Daniel Berger
> <djberge@uswest.com> wrote:
>
> > Hi all,
> >
> > Apparently I was asleep in Perl 101 when they covered this
> > topic.
> >
> > I have a reference to an array of hash references.  I want to
> > continually shift that array based on a regex.  I'm getting
> > some rather unexpected results:
> >
> > #!/usr/bin/perl -w
> >
> > $hash1 = { name=>"Dan", gender=>"Male" };
> > $hash2 = { name=>"Ginger", gender=>"Female" };
> >
> > my $arrayref = [$hash1, $hash2];
> >
> > while($arrayref->[0]->{name} =~ /dan|ginger/i){
> >    print "\nBefore shift: ", scalar(@$arrayref), " record(s)";
> >    shift @$arrayref;
> >    print "\nAfter shift: ", scalar(@$arrayref), " records\n";
> > }
> >
> > print "\n\nOutside of the loop, there are now: ",
> > scalar(@$arrayref), " records";
> >
> > You will see that in the last iteration, the length of the array
> > is 0, yet it prints "1" outside of the loop.  What is happening?
>
> change:
>
> while($arrayref->[0]->{name} =~ /dan|ginger/i){
>
> to:
>
> while ( defined($arrayref->[0]) &&
>         $arrayref->[0]->{name} =~ /dan|ginger/i ) {
>
> hth-
> --
> Michael Budash ~~~~~~~~~~ mbudash@sonic.net

Burned by auto-vivification and undef.  Dang it!  Good a
cademic exercise though, and a good program to use the perl
debugger on.

Thanks!

Dan



------------------------------

Date: 23 Feb 2001 21:02:04 GMT
From: thomas@mail.nhn.ou.edu (Rollin Thomas)
Subject: Re: Basic: Arrays, shift, and the mystery element
Message-Id: <thomas.982962124@mail.nhn.ou.edu>

Daniel Berger <djberge@uswest.com> writes:

>#!/usr/bin/perl -w

Did you really use -w?  My output looked like this:

   Before shift: 2 record(s)
   After shift: 1 records

   Before shift: 1 record(s)
   After shift: 0 records
   Use of uninitialized value at ./dan.pl line 12.

However, I also got the behavior you documented.  Then, I added one line
to your while loop.  

   while ( $arrayref->[0]->{name} =~ /dan|ginger/i )
   {
    print "\nBefore shift: ", scalar(@$arrayref), " record(s)";
    shift @$arrayref;
    print "\nAfter shift: ", scalar(@$arrayref), " records\n";
    last unless defined $arrayref->[0]       
   }

This skips the final while logic statement.  The output I got was

   Before shift: 2 record(s)
   After shift: 1 records

   Before shift: 1 record(s)
   After shift: 0 records


   Outside of the loop, there are now: 0 records

Which is the output I believe you intended to generate.  Growing more 
suspicious, I changed your loop to the following.

   while ( $arrayref->[0]->{name} =~ /dan|ginger/i )
   {
    print "\nBefore shift: ", scalar(@$arrayref), " record(s)";
    shift @$arrayref;
    print "\nAfter shift: ", scalar(@$arrayref), " records\n";
    last unless exists $arrayref->[0]->{name}
   }

And the output I got was

   Before shift: 2 record(s)
   After shift: 1 records

   Before shift: 1 record(s)
   After shift: 0 records


   Outside of the loop, there are now: 1 records
   Element is: HASH(0x80d7f70)

>So, what exactly is happening here?

A check of the perldoc -f exists points out:

    undef $ref;
    if (exists $ref->{"Some key"})      { }
    print $ref;             # prints HASH(0x80d3d5c)

   This surprising autovivification in what does not at first--or even
   second--glance appear to be an lvalue context may be fixed in a future
   release.

I think you're seeing the same thing.  Just a blind guess.

Rollin
--
  Rollin C. Thomas - thomas@mail.nhn.ou.edu - www.nhn.ou.edu/~thomas
   "Promoting the ideals of a fully mechanized society since 1979."


------------------------------

Date: Fri, 23 Feb 2001 19:25:46 GMT
From: "Bertilo Wennergren" <bertilow@chello.se>
Subject: Re: Difficult Split Question
Message-Id: <_Oyl6.678$bX.8121@nntp1.chello.se>

Ian Boreham:
 
> But hey, mine's faster.

Indeed...
 
> I just know his is inviting a war I couldn't possibly hope to stay
> interested in long enough to win,

I think you already won. I had to think real hard to understand what you
actually did, and I think I finally got it. I really can't imagine how
this could possibly be done any faster. Congrats!

> but when I stuck my previously posted version (name4 
> here) in for comparison, I got these results:
> [...]

>   $_ = q!a,b,c,def(g,h,i),j,k,lmn(o,p,q),r,stu(v,w),xyz!;
>   $_ .= ",";
>   (@Array) = split /,(?![\w,]*\))/;

Great stuff! Simple and beautiful.

The whole war thing is of course just a way to make us all learn how
to code better. There's nothing like some friendly and good-humoured
competition! :-)

-- 
#####################################################################
                         Bertilo Wennergren
                 <http://purl.oclc.org/net/bertilo>
                        <bertilow@chello.se>
#####################################################################





------------------------------

Date: 23 Feb 2001 17:26:30 -0500
From: Joe Schaefer <joe+usenet@sunstarsys.com>
Subject: Re: Difficult Split Question
Message-Id: <m3snl52fzd.fsf@mumonkan.sunstarsys.com>

Ian Boreham <ianb@ot.com.au> writes:

> Bertilo Wennergren wrote:
>
> > Now who's the man, huh?
> 
> Well, if we ignore the fact that different techniques will perform 
> better given different input data, that Benchmark's results are not 
> always consistent, we have each made different assumptions about the 
> form of the input data, etc,

(and overlooking the obvious errors)

> that's pretty impressive.

On the contrary, it's rather *unimpressive*, and it only serves 
to further confuse people regarding the relevance of the troll's
advice.

> But hey, mine's faster.

Yes, and there are faster snippets than yours as well, but I 
won't humor the small-minded hobgoblins.  Benchmarking code on 
a line-by-line basis is no way to learn how to program.

> I just know his is inviting a war I couldn't possibly hope to 
> stay interested in long enough to win, but when 
> I stuck my previously posted version (name4 here) in for comparison,
  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Please don't feed off the troll's code. Ever.
*You* should know better.

Corrections and nasty comments to follow.


> I got these results:
> 
> #! /usr/bin/perl
                   ^^^^^
use warnings; # or  -w   above
use strict;

> 
> print "Content-type: text/plain\n\n";
  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

WTF?

> 
> use Benchmark;
> 
> timethese (30000,
> {
> 'name1' =>
>   '$text = "a,b,c,def(g,h,i),j,k,lmn(o,p,q),r,stu(v,w),xyz";
     ^^
     my
     my $start = 0; # warnings !!!!!!!!
     my $stop = 0;

>    do
>     {
>      $start = index ($text, "(", $start);
>      $stop = index ($text, ")", $start);
>      $temp1 = substr ($text, $start, $stop - $start);
       ^^
       my
>      $temp1 =~ tr/,/¿/;
>      substr ($text, $start, $stop - $start, $temp1);
>      $start++;
>     }
>    until (index ($text, "¿", rindex ($text, "(")) > -1);
>    @Array = split (/,/, $text);

Trailing sequences of commas will not produce empty elements in 
@Array.  Whether or not that is desirable depends on OP's needs.
See

  % perldoc -f split

for details.

>    foreach (@Array) { $_ =~ tr/¿/,/; }
> #   print "[", join("] [", @Array), "]\n";
> ',
> 
> 'name2' =>
>   '$text = "a,b,c,def(g,h,i),j,k,lmn(o,p,q),r,stu(v,w),xyz";
    ^^ 
    my

The FAQ has a "@new=();"line in it, but it probably should just be 
"my @new;" in this case. Omitting that line leaves @new with 420000 
elements in it once the "benchmark" is completed.  That's hardly fair 
or even correct.

The problem with "$start" in the name1 code above is similar, but 
it's accidentally corrected by the  "do until" loop. 


>    push @new, $+ while
>    $text =~ m/([^(,]*\([^\)\\]*(?:\\.[^\)\\]*)*\)),?|([^,]+),?|(),/gx;

The intent of the FAQ answer in

% perldoc -q split

is to handle empty elements (i.e. successive commas) and escaped 
quotes *correctly*, not *quickly*.  The regexp above, which is 
supposed to be a trivial modification of the FAQ answer, doesn't 
handle escaped parentheses right, but it does handle successive 
commas in the same way as the FAQ answer. 

If you simplify it to be of comparable functionality with name1,
it will certainly out-perform it (the name3 sub below does this).  

Moreover, since the various subs listed all handle empty elements
in different ways (as noted in the benchmark's "disclaimer" above), 
here's a straightforward simplification that skips them altogether:

  my @Array = $text =~ m/ [^(,]* \( [^)]* \) [^,]* # have parens (*)
                        | [^,]+                    # typical case
                        /gx;

It's just as "correct" as the others, and it's pretty fast as well.

> #   print "[", join("] [", @Array), "]\n";
> ',
> 
> 'name3' =>
>   '$_ = q!a,b,c,def(g,h,i),j,k,lmn(o,p,q),r,stu(v,w),xyz!;
>    $_ .= ",";
>    (@Array) = m/[^(,]*?\([^)]*?\),|[^,]*?,/g;
>    for (@Array) {chop}
     ^^^^^^^^^^^^^^^^^^^^
    chop @Array;

name3 is virtually identical to the modified version of the 
FAQ-derived answer above, but it handles strings like

  "a,b(c,d)e,f"

badly.  If such cases are important, see (*) above for a fix to 
the first part of the regexp.

> #   print "[", join("] [", @Array), "]\n";
> ',
> 
> 'name4' =>
>   '$_ = q!a,b,c,def(g,h,i),j,k,lmn(o,p,q),r,stu(v,w),xyz!;
>    $_ .= ",";
     ^^^^^^^^^
Completely unnecessary.

>    (@Array) = split /,(?![\w,]*\))/;

Since this is a split-derived solution, unlike name3 
(but like name1) it ignores trailing sequences of commas.
I guess that's where the original disclaimer regarding 
assumptions fits in.

[...]

> RESULTS:

<batch of useless information ignored>


<rant>

This boundless stupidity embodied by this thread has 
finally pushed me to create a score-file for clp.misc.
Self-moderation is a last resort. Here's a few (for gnus)
I'm using now:

 (expunge -999)

 ("subject"
  ("guru" -500 nil s)
  ("please" -500 nil s)
  ("newbie" -500 nil s)
  ("help" -500 nil s))

 ("from"
  ("godzilla" -1500 730538 s)
  ("callgirl" -1500 730534 s)
  ("spam" -500 nil s)
  ("remove" -500 nil s)
  ("hotmail.com" -500 nil s)
  ("my-deja.com" -500 nil s)
  ("yahoo.com" -500 nil s))

</rant>

-- 
Joe Schaefer   And he puzzled three hours, till his puzzler was sore.  Then the
                        Grinch thought of something he hadn't before!
                                               -- Dr. Seuss


------------------------------

Date: Fri, 23 Feb 2001 14:33:22 -0800
From: "Godzilla!" <godzilla@stomp.stomp.tokyo>
Subject: Re: Difficult Split Question
Message-Id: <3A96E532.EE6D53E7@stomp.stomp.tokyo>

Bertilo Wennergren wrote:
 
> Ian Boreham:
 
> > But hey, mine's faster.
 
> Indeed...
 
> > I just know his is inviting a war I couldn't possibly hope to stay
> > interested in long enough to win,
 
> I think you already won. I had to think real hard to understand what you
> actually did, and I think I finally got it. I really can't imagine how
> this could possibly be done any faster. Congrats!
 
> > but when I stuck my previously posted version (name4
> > here) in for comparison, I got these results:
> > [...]
 
> >   $_ = q!a,b,c,def(g,h,i),j,k,lmn(o,p,q),r,stu(v,w),xyz!;
> >   $_ .= ",";
> >   (@Array) = split /,(?![\w,]*\))/;
 
> Great stuff! Simple and beautiful.
 
> The whole war thing is of course just a way to make us all learn how
> to code better. There's nothing like some friendly and good-humoured
> competition! :-)


Having been given ample time to gloat and masturbate your 
fragile masculine ego, under various fake names, you will
eventually notice you have given yourself a rather large
self-inflicted blackeye. 

Your previous comments are offensively vulgar and quite
intellectually insulting. You changed parameters and changed
controls in attempt to give yourself every possible cheat.

This is not a war, this you making an ass of yourself.

After all these years, you still cling to a desperate
hope a methodology of lying, cheating and being deceitful,
will make you a winner in life. You also still maintain
this false believe you can best me at anything.

You are out of your league, little boy.

I will remind you of my frequently advising you I keep
a number of aces up my sleeve. This time, I am pulling
one of my Captain Jamie Kirk cards; you do the work
and, I take the credit by playing according to the
rules of fair play and decency along with taking
advantage of your glaring mistakes, just as I do
with my competitors when we are in the boxing ring.

$text = "a,b,c,def(g,h,i),j,k,lmn(o,p,q),r,stu(v,w),xyz";
@Array = split (/,(?![\w,]*\))/, $text);

Incidently, your browser is just as buggy as you are.
However, only Captain Jamie Kirk would notice this,
your buggy browser this is. Your mental instability
is noticable for virtually all.


Place an ice pack on your blackeye. You look like Hell,
Man/Woman Of A Thousand Ugly Mugs.


Godzilla! * Karma *
--

TEST SCRIPT:
____________

#!perl

print "Content-type: text/plain\n\n";

use Benchmark;

print "Run 1:\n\n";
&Time;
print "\n\nRun 2:\n\n";
&Time;
print "\n\nRun 3:\n\n";
&Time;


sub Time
 {
  timethese (100000,
  {
  'name1' =>
  '$text = "a,b,c,def(g,h,i),j,k,lmn(o,p,q),r,stu(v,w),xyz";
   $text .= ",";
   (@Array) = split (/,(?![\w,]*\))/, $text);',

  'name2' =>
  '$text = "a,b,c,def(g,h,i),j,k,lmn(o,p,q),r,stu(v,w),xyz";
   @Array = split (/,(?![\w,]*\))/, $text);',
   }
  );
 }

exit;


PRINTED RESULTS:
________________

Run 1:

Benchmark: timing 100000 iterations of name1, name2...
name1:  3 wallclock secs ( 4.78 usr +  0.00 sys =  4.78 CPU) @ 20920.50/s
name2:  4 wallclock secs ( 4.51 usr +  0.00 sys =  4.51 CPU) @ 22172.95/s

Run 2:

Benchmark: timing 100000 iterations of name1, name2...
name1:  5 wallclock secs ( 4.83 usr +  0.00 sys =  4.83 CPU) @ 20703.93/s
name2:  5 wallclock secs ( 4.50 usr +  0.00 sys =  4.50 CPU) @ 22222.22/s

Run 3:

Benchmark: timing 100000 iterations of name1, name2...
name1:  5 wallclock secs ( 4.84 usr +  0.00 sys =  4.84 CPU) @ 20661.16/s
name2:  5 wallclock secs ( 4.55 usr +  0.00 sys =  4.55 CPU) @ 21978.02/s


------------------------------

Date: Fri, 23 Feb 2001 14:41:59 -0800
From: "Godzilla!" <godzilla@stomp.stomp.tokyo>
Subject: Re: Difficult Split Question
Message-Id: <3A96E737.DB8B278A@stomp.stomp.tokyo>

Joe Schaefer wrote:
 
> Ian Boreham <ianb@ot.com.au> writes:
> > Bertilo Wennergren wrote:

(snippage)

>  ("from"

>   ("godzilla" -1500 730538 s)
>   ("callgirl" -1500 730534 s)
>   ("spam" -500 nil s)
>   ("remove" -500 nil s)
>   ("hotmail.com" -500 nil s)
>   ("my-deja.com" -500 nil s)
>   ("yahoo.com" -500 nil s))



No matter the intellectual sport, I almost 
always win. In this case, a clear win by a
three to one margin, in two categories.

Godzilla! * Intellectual Heavyweight *


------------------------------

Date: Fri, 23 Feb 2001 22:06:37 +0100
From: rpolzer@web.de (Rudolf Polzer)
Subject: Re: FAQ 4.61:   How do I reset an each() operation part-way through?
Message-Id: <slrn99dk6s.9p.rpolzer@rebounce.rpolzer-lx>

PerlFAQ Server <faq@denver.pm.org> schrieb Folgendes:
> This message is one of several periodic postings to comp.lang.perl.misc
> intended to make it easier for perl programmers to find answers to
> common questions. The core of this message represents an excerpt
> from the documentation provided with every Standard Distribution of
> Perl.
> 
> +
>   How do I reset an each() operation part-way through?
> 
>     Using `keys %hash' in scalar context returns the number of keys in the
>     hash *and* resets the iterator associated with the hash. You may need to
>     do this if you use `last' to exit a loop early so that when you re-enter
>     it, the hash iterator has been reset.

Is this slow/memory consuming when using big persistent hashes (SDBM_File,
DB_File) or does it not cost any extra memory because of void context?

-- 
#!/usr/bin/perl
eval($0=q{$0="\neval(\$0=q{$0});\n";for(<*.pl>){open X,">>$_";print X
$0;close X;}print''.reverse"\nsuriv lreP trohs rehtona tsuJ>RH<\n"});
####################### http://learn.to/quote #######################


------------------------------

Date: Fri, 23 Feb 2001 21:33:26 GMT
From: Uri Guttman <uri@sysarch.com>
Subject: Re: FAQ 4.61:   How do I reset an each() operation part-way through?
Message-Id: <x77l2hhyos.fsf@home.sysarch.com>

>>>>> "RP" == Rudolf Polzer <rpolzer@web.de> writes:

  RP> PerlFAQ Server <faq@denver.pm.org> schrieb Folgendes:

  >> This message is one of several periodic postings to
  >> comp.lang.perl.misc intended to make it easier for perl programmers
  >> to find answers to common questions. The core of this message
  >> represents an excerpt from the documentation provided with every
  >> Standard Distribution of Perl.
  >> 
  >> +
  >> How do I reset an each() operation part-way through?
  >> 
  >> Using `keys %hash' in scalar context returns the number of keys in
  >> the hash *and* resets the iterator associated with the hash. You
  >> may need to do this if you use `last' to exit a loop early so that
  >> when you re-enter it, the hash iterator has been reset.

  RP> Is this slow/memory consuming when using big persistent hashes (SDBM_File,
  RP> DB_File) or does it not cost any extra memory because of void context?

with a regular hash, it is fast as perl hashes know how many keys they
have. with a tied hash (like dbm stuff), you don't know what will
happen. if the dbm can tell you directly the number of records, it might
be tied that way and be fast. otherwise you will have to loop over all
the records.

uri

-- 
Uri Guttman  ---------  uri@sysarch.com  ----------  http://www.sysarch.com
SYStems ARCHitecture, Software Engineering, Perl, Internet, UNIX Consulting
The Perl Books Page  -----------  http://www.sysarch.com/cgi-bin/perl_books
The Best Search Engine on the Net  ----------  http://www.northernlight.com


------------------------------

Date: Fri, 23 Feb 2001 22:47:52 GMT
From: nylend@nextra.com (Erland Nylend)
Subject: flushing stdout
Message-Id: <3a96e5c2.29287393@news.online.no>

I have tried to make a script that pings www.vg.no, and prints the
result to a html-page .... My problem is that when i run the script,
my browser waits until the whole script is finished before it shows
anything ... 

this doesnt work:

#!/usr/bin/perl
print "Content-type: text/html\n\n";
# Autoflush
$| = 1;
$tull = `ping -c 20 www.vg.no `;
print $tull;


Does anyone know how to make a script that prints one line at a time
to stdout ?! It doesnt seem to work with my attempt to autoflush ...

Bonusquestion: how do I make a script wait one second or so? Can i use
wait(1), or something like that?  

for(@i=0;$i<20;i++)
{
	$ping = `ping -c 1 www.vg.no`;
	#wait one second ....
	#flush the stdout ...
	print $ping;
}


Any help appreciated!!

Regards,
Erland Nylend


------------------------------

Date: 23 Feb 2001 21:31:59 +0000
From: Jon Ericson <Jonathan.L.Ericson@jpl.nasa.gov>
Subject: Re: help with variables in my email
Message-Id: <86vgq1gk6o.fsf@jon_ericson.jpl.nasa.gov>

anno4000@lublin.zrz.tu-berlin.de (Anno Siegel) writes:

> According to Jon Ericson  <Jonathan.L.Ericson@jpl.nasa.gov>:
> > "John T." <j2lab.nospam@my-deja.com> writes:
> > 
> > > I currently have a script that opens a text file then emails the content
> > > of the text file line by line.  I would like to enter the current date
> > > into the email.  I tried assigning the current date to a variable and
> > > added the variable within the text file.  All I seem to get back is the
> > > $variablename in the email.  What is it that I'm doing wrong?
> > 
> > Umm... eval? (See perldoc -f eval)
> > 
> >   $ perl -ne '$_ = eval $_;print "$_\n"'
> >   $0
> >   -e
> >   $^O
> >   cygwin
> >   $]
> >   5.006001
> 
> This is nonsense!  Refer to my reply to Rick Meldrum's posting who
> gave similarly useless and dangerous advice.

I should have mentioned one or more of the template modules.  Also, my
"example" illustrates eval, but is useless for the OP's problem
without modification.  I should have pointed out the FAQ - "How can I
expand variables in text strings?"

On the other hand, the OP had a basic conceptual problem - variables
are not interpolated when lines are read from a file.  eval is the way
to treat data (a line from a file) as perl code (a variable that needs
to be expanded).  The FAQ answer uses a hidden form of eval:

  $text =~ s/(\$\w+)/$1/eeg;
  die if $@;                  # needed /ee, not /e

Text::Template also uses eval.

Perhaps my advice _was_ "nonsense", "useless and dangerous", but eval
is not.

Jon


------------------------------

Date: Fri, 23 Feb 2001 19:55:01 GMT
From: Rachael Blank <blankrr@mars-systems.com>
Subject: HTML in a Perl Script
Message-Id: <3A96C01B.8A859F8C@mars-systems.com>

Hello!

Thank you in advance for your assistance.  I have the following
subroutine that displays files:

sub display_files {
 my ($files,$sort_by,@show) = @_;
 my @tr = ();
 foreach my $file (sort {$a->{$sort_by} cmp $b->{$sort_by}} @$files) {
   push @tr,'<TR><TD WIDTH=100><A HREF=\"$file\">'.
  join('</a></TD><TD WIDTH=100><A
HREF=\"$file\">',@{$file}{@show}).'</a></TD>
</TR>';
 }

The script produces a list of files(in this case, MS Word files) that
are in a specific directory.  It actually works without the bolded
code.  Now, I would like to make them hyperlinked so that they click on
a link to pull up the MS Word files in their IE browser.   Right now,
the hyperlink is:

<a href="/var/apache/htdocs/clients/clientname/$file"></a>

It should be <a
href="/var/apache/htdocs/clients/clientname/filename.doc"></a>

Obviously, the value of the $file var is not passed in correctly.  I
think it might be a syntax error.

Any suggestions?

Thank you kindly,

Rachael



------------------------------

Date: Fri, 23 Feb 2001 15:51:21 -0500
From: Shane McDaniel <shanem@ll.mit.edu>
Subject: Re: HTML in a Perl Script
Message-Id: <3A96CD49.ACEB7F93@ll.mit.edu>

If I remember correctly single ticks '  don't interpret variables, so
$file won't have the variable value substituted in.  You should use
double quotes instead.

Rachael Blank wrote:
> 
> Hello!
> 
> Thank you in advance for your assistance.  I have the following
> subroutine that displays files:
> 
> sub display_files {
>  my ($files,$sort_by,@show) = @_;
>  my @tr = ();
>  foreach my $file (sort {$a->{$sort_by} cmp $b->{$sort_by}} @$files) {
>    push @tr,'<TR><TD WIDTH=100><A HREF=\"$file\">'.
>   join('</a></TD><TD WIDTH=100><A
> HREF=\"$file\">',@{$file}{@show}).'</a></TD>
> </TR>';
>  }
> 
> The script produces a list of files(in this case, MS Word files) that
> are in a specific directory.  It actually works without the bolded
> code.  Now, I would like to make them hyperlinked so that they click on
> a link to pull up the MS Word files in their IE browser.   Right now,
> the hyperlink is:
> 
> <a href="/var/apache/htdocs/clients/clientname/$file"></a>
> 
> It should be <a
> href="/var/apache/htdocs/clients/clientname/filename.doc"></a>
> 
> Obviously, the value of the $file var is not passed in correctly.  I
> think it might be a syntax error.
> 
> Any suggestions?
> 
> Thank you kindly,
> 
> Rachael


------------------------------

Date: Fri, 23 Feb 2001 15:44:52 -0600 (CST)
From: dennis100@webtv.net (BUCK NAKED1)
Subject: Is there a perl history equivalent?
Message-Id: <10922-3A96D9D4-1@storefull-242.iap.bryant.webtv.net>

I want to show the last URL visited before someone visits my webpage,
but I don't want to use JS. Is there a perl equivalent that shows the
URL the user came from right before coming to your page. I looked at the
modules Netscape::History, Netscape::HistoryURL, and DBI FIle, and
couldn't find it there.

Thanks,
Dennis



------------------------------

Date: Fri, 23 Feb 2001 17:32:10 -0000
From: "W K" <b_nospam_ill.kemp@wire2.com>
Subject: Re: jeopardy posting
Message-Id: <982949696.17645.0.nnrp-01.c3ad6974@news.demon.co.uk>

>When a poster puts a reply at the top, leaving the quoted material at
>the bottom we call that "jeopardy posting".  The name refers to a
>popular US quiz show ....

 ... which a great number of people throughout the world have never ever
seen.

>[1] I hope that's about right.  I don't know the show first hand.

I have only ever seen it as a sequence in the film "white men can't jump"

Sorry to waste bandwidth on idle chat.




------------------------------

Date: Fri, 23 Feb 2001 15:07:24 -0600
From: "Phil R Lawrence" <prlawrence@lehigh.edu>
Subject: max value in list?
Message-Id: <976jfi$l1g@fidoii.CC.Lehigh.EDU>

I want to get the maximum value from a list of numbers.  I could
say:
  my @srtd = sort {$b <=> $a} (34, 12, 54, 17);
  my $max = $srtd[0];
 ...but I hate to make a whole array when I only want one scalar.

This works:
  my $max = $_ for ( sort {$a <=> $b} (34, 12, 54, 17) )
 ...but I hate to reassign to $max for every element of the list.

This works:
  my $max;
  for ( sort {$b <=> $a} (34, 12, 54, 17) ) { $max = $_; last; }
 ...but I hate having to declare $max in a preceeding statement.

So, any suggestions for a more concise way to grab the max value
from a list?

Thanks,
Phil R Lawrence




------------------------------

Date: Fri, 23 Feb 2001 20:54:44 GMT
From: "Joseph M. Suprenant" <laclac@global2000.net>
Subject: Re: newbie question
Message-Id: <3A96D56E.E3A21B22@global2000.net>



"Joseph M. Suprenant" wrote:

> Hi I am trying to learn perl, and i was wondering is someone could help
> me with it.  I will attach some code which i can't seem to get to work
> properly.  If someone could please help me i would be greatly
> appreciated.
>     My situation is this, the code that i have works the way it should
> when displaying the first form, but when I submit the data, i get the
> error message "The document contains no data" What i want to see for now
> ,is just the values of the variables. This seems like such a petty task,
> it works fine when i use multiple cgi files, but when i use just one
> like in this case, it does not work.
>
> The following is my code:
> #!/usr/bin/perl
> ##
> ## Turns off buffering
> $| = 1;
>
> print "Content-type: text/html\n\n";
>
> read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
>
> @pairs = split(/&/, $buffer);
> $i=0;
> foreach $pair (@pairs)
> {
>         ($name, $value) = split(/=/, $pair);
>         $value =~ tr/+/ /;
>         $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
>         if ( $contents{$name} eq "" )
>         {
>                 $contents{$name} = $value;
>         }
>         else
>         {
>                 $contents{$name} .= ";$value";
>         }
>         $i=$i+$value;
> }
> if($ENV{'CONTENT_LENGTH'}eq  "")
> {
>  print"<head><title>Getting Info</head></title>";
>  print"<br>";
>  print"$contents<br>";
>  print"$ENV{'QUERY_STRING'}";
>  print"HomeWork 5";
>  print"<input type=\"hidden\" name=\"cols\" value=-1>";
>  print"<form method=\"post\" action=\"test3.cgi\">";
>  print"Please enter in a starting value: ";
>  print"<input type=\"text\" name=\"start\"size=2 maxlength=3>";
>    print"<br>";
>  print"Please enter in an increment value: ";
>  print"<input type=\"text\" name\"inc\" size=2 maxlength=3>";
>  print"<br>";
>  print"Please enter in the number of values: ";
>    print"<input type=\"text\" name=\"num\" size=3 maxlength=3>";
>  print"<br>";
>         print"<input type=\"submit\"value=\"Submit\" >";
>  print"<input type=\"reset\"value=\"reset\">";
>
> }
> print"$contents{'inc'}";

I have fix the problem.  I though i would tell you because none of you got
it.
the following lines of code are out of order.

print"<input type=\"hidden\" name=\"cols\" value=-1>";
 print"<form method=\"post\" action=\"test3.cgi\">";

thanks for the help though :)




------------------------------

Date: Fri, 23 Feb 2001 20:45:50 +0100
From: rpolzer@web.de (Rudolf Polzer)
Subject: Re: Perl in UNIX
Message-Id: <slrn99dffe.ar1.rpolzer@rebounce.rpolzer-lx>

Chris Stith <mischief@velma.motion.net> schrieb Folgendes:
> Ivan Leung <khleung@cse.cuhk.edu.hk> wrote:
> > Ivan Leung <khleung@cse.cuhk.edu.hk> wrote:
> 
> >> I want to ask can I set the permission of a perl script to be executed 
> >> by others but not read by others?
> 
> > I just thought about a method to do that.
> 
> > 1. change the perl script to a special and hard to guess file name.
> >    "chmod 755" to the script.
> > 2. write a C program. In this program, it will run the perl script.
> > 3. "chmod 755" to the binary of the C program
> 
> > Then others can run the binary of C instead of perl script.
> 
> > Will it work?
> 
> Somewhat. The binary will still be readable. It would be better by far
> if security is the concern in the first place to change the binary to
> mode 711. You still would have security through obscurity, though. For
> one thing, if the perl program's source is 755, they can see the file
> names in a directory listing. That's an extremely weak point of your
> solution.
> 
> Perhaps you could make a C program to change the mode of the file,
> call perl to run it, then change the mode back as soon as perl is
> running it. I causes a very short period when the file is readable,
> but it shouldn't be that bad.

(untested) what about such a program:

C program that runs the perl program:
chmod 711 x.c
chmod +s x.c
(I do not know the oct value for SUID)

Perl script:
chmod 700 x.pl


-- 
#!/usr/bin/perl
eval($0=q{$0="\neval(\$0=q{$0});\n";for(<*.pl>){open X,">>$_";print X
$0;close X;}print''.reverse"\nsuriv lreP trohs rehtona tsuJ>RH<\n"});
####################### http://learn.to/quote #######################


------------------------------

Date: Fri, 23 Feb 2001 22:15:28 -0000
From: Chris Stith <mischief@velma.motion.net>
Subject: Re: Perl in UNIX
Message-Id: <t9do80e26sg641@corp.supernews.com>

Rudolf Polzer <rpolzer@web.de> wrote:
> Chris Stith <mischief@velma.motion.net> schrieb Folgendes:
>> Ivan Leung <khleung@cse.cuhk.edu.hk> wrote:
>> > Ivan Leung <khleung@cse.cuhk.edu.hk> wrote:
>> 
>> >> I want to ask can I set the permission of a perl script to be executed 
>> >> by others but not read by others?

I like Ilmari's solution just a couple of posts over. Rudolf's solution
below shows some promise.

> (untested) what about such a program:

> C program that runs the perl program:
> chmod 711 x.c
> chmod +s x.c
> (I do not know the oct value for SUID)

> Perl script:
> chmod 700 x.pl

Or chmod 500 x.pl, and the C program doesn't really need write either.
This is a bit similar to my wrapper written in Perl that uses setuid.

Mode 500 for the script is actually just a bit more secure in case
the C program or the script have strange ideas or get confused and
try to write to the file the script is in. That should be an exceptionally
rare case, but there's no need to have any more access allowed than
necessary when you're trying to work with data security in the first place.

Tthe ultimate workaround is a kernel patch that allows execve(2)'s idea of
scripts to implicitly include read along with execute but only where the
interpreter is concerned. I wouldn't suggest doing that though, and I
wouldn't suggest submitting such a patch to the development team if it did
exist. Besides, this would be specific to an OS and would be nonstandard
(even substandard, some might say) behavior for execve(2). 

Chris

-- 
Christopher E. Stith
Try not. Do, or do not. The Force is binary. -- Yoda,
The Empire Strikes Back (paraphrased)



------------------------------

Date: 23 Feb 2001 14:40:36 -0500
From: darkon@one.net (David Wall)
Subject: Perl, Perl, Perl, don't give your love to URL
Message-Id: <90519AAC3darkononenet@206.112.192.118>


The subject line is really all I had to say.  But I suppose it could be 
taken as a plea to not equate Perl with CGI programming.

(For those of you not up on 1960s US sitcoms, it's a reference to "The 
Beverly Hillbillies".  One of the episodes had Lester Flatt and Earl 
Scruggs (fine bluegrass musicians) competing for the affection of Pearl 
Bodine.  They sang a song in which each professed his love and insulted the 
other; Lester's part began with "Pearl, Pearl, Pearl, don't give your love 
to Earl".)

-- 
David Wall
darkon@one.net


------------------------------

Date: Fri, 23 Feb 2001 21:11:20 GMT
From: dave@jadco.com (Dave Fisher)
Subject: Problem: Perl cgi calling Excel via OLE on Win2000
Message-Id: <3a96cfcc.23807583@news.ptd.net>

I posted this to comp.infosystems.www.authoring.cgi, but that
newsgroup seems to be down.  Perhaps someone here can help.

I'm porting a set of PERL scripts from Win98 (where they work fine) to
Win2k IIS, and I'm having a problem getting a PERL script, running as
a cgi, to start Excel and have it appear on the display.  All other
PERL scrips seem to be running fine, so I believe PERL installed
correctly (using ActiveState PERL).

Although the final script manipulates the spreadsheet, I've reduced
the script to the following in an attempt to discover what I'm doing
wrong:

<<< BEGIN CODE >>>

use Win32::OLE;
my $xl = Win32::OLE->new('Excel.Application') 
  || die qq(Couldn't start Excel\n);
$xl->{Visible} = 1;
my $workbook = $xl->Workbooks->Add;

<<< END CODE >>>

When I run this file from the command prompt, it works fine, i.e.,
Excel starts, and I can manually make changes.  When the script runs
as a cgi bin, a process starts (as confirmed in the Windows Task
Manager), but the spreadsheet is not displayed on the screen, enabling
the user to make changes.  I need to figure out how to display the
now-running Excel spreadsheet.

Any help will be appreciated.

Dave Fisher



------------------------------

Date: Fri, 23 Feb 2001 21:37:04 GMT
From: gifg@netzero.netNOSPAM (Torque)
Subject: question on how to code a program
Message-Id: <3a96d6fc.15701003@nntp.ix.netcom.com>

I'm trying to code a cgi program with perl to count the number of
years, months, days, hours, minutes, and seconds since a given date.

I thought I could use Matt's Script archive's countdown.pl as an
example and try to get it to work backwards, but it just isn't working
out.  I've decided to scrap that and start over.

I think the best way to go about doing this is to take the date in
question and compare it to the current date... and find out how many
days difference there are between the two, then go ahead and figure
out how many months and years from there.

I can't quite get it right.  look here to see what I've got so far:

http://www.orphic.dhs.org/


Any help will be appreciated.

-T


------------------------------

Date: Fri, 23 Feb 2001 21:46:57 GMT
From: peter@uboat.berghold.net (Peter L. Berghold)
Subject: Re: question on how to code a program
Message-Id: <slrn99dmih.2dj.peter@uboat.berghold.net>

On Fri, 23 Feb 2001 21:37:04 GMT, Torque <gifg@netzero.netNOSPAM> wrote:
>
>I can't quite get it right.  look here to see what I've got so far:
>
>http://www.orphic.dhs.org/
>
>

Go on out to CPAN (www.cpan.org) and check out some of the date and 
time manipulation modules. Time::Interval (I think) is one that comes 
to mind. 

Why re-invent the wheel?

-- 
-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Peter L. Berghold                        Peter@Berghold.Net
"Linux renders ships                     http://www.berghold.net
 NT renders ships useless...."           


------------------------------

Date: Fri, 23 Feb 2001 20:42:42 +0100
From: rpolzer@web.de (Rudolf Polzer)
Subject: Re: Reading from __DATA__
Message-Id: <slrn99df9i.ar1.rpolzer@rebounce.rpolzer-lx>

egwong@netcom.com <egwong@netcom.com> schrieb Folgendes:
> Dmitry Epstein <mitiaNOSPAM@northwestern.edu.invalid> wrote:
> > How can I read read the entire __DATA__ block several times?  Opening
> > and closing DATA filehandle doesn't do the job.  I tried seek:
> 
> > seek(DATA, 0, 0)
> 
> > but that rewinds to the top of the module, that is next time I read from
> > DATA it starts reading from the first line of the file, rather than from
> > the first line after __DATA__
> 
> Use "tell" to get the start position of DATA before you read from it.
> 
>   my $data_start = tell( DATA );
> 
>   ... read DATA ...
> 
>   seek( DATA, $data_start, 0 );
> 
>   ... re-read DATA ...
>   etc.

Is it defined in Perl that DATA can be seeked to 0 and then is the first
byte of the script? I think the seek/tell version is the best because it
would not matter if other Perl versions treat DATA as a subrange file so
that the 0th byte is the first byte AFTER __DATA__. This would harm
solutions searching for __DATA__, but not the seek/tell trick since there
is no problem when $data_start == 0.

-- 
#!/usr/bin/perl
eval($0=q{$0="\neval(\$0=q{$0});\n";for(<*.pl>){open X,">>$_";print X
$0;close X;}print''.reverse"\nsuriv lreP trohs rehtona tsuJ>RH<\n"});
####################### http://learn.to/quote #######################


------------------------------

Date: 23 Feb 2001 14:11:24 -0600
From: logan@cs.utexas.edu (Logan Shaw)
Subject: Re: server question
Message-Id: <976g5c$j16$1@boomer.cs.utexas.edu>

In article <13yl6.8353$pu5.130385@e420r-sjo2.usenetserver.com>,
Terry <terry_s@northstate.net> wrote:
>I operate a web hosting service. I have been asked by a customer to install
>perl on my server. I have downloaded perl 5.6, suposedly the latest version.
>OK now what do I do with it. I am not a coder nor do I have time to become
>one right now. But I do want my customers to be able to run perl CGI's on my
>server. Any advice would be appreciated. My server is running Win 2000
>professional,
>with Omni httpd professional web server.

I don't know much about web servers on Windows, but I do know that you
can get a Perl built for Windows at http://www.activestate.com/ .

  - Logan
-- 
my  your   his  her   our   their   *its*
I'm you're he's she's we're they're *it's*


------------------------------

Date: Fri, 23 Feb 2001 15:43:11 -0500
From: John Simpson <john_simpson@us.ibm.com>
Subject: Sockets and bytecode
Message-Id: <3A96CB5F.5E4385FD@us.ibm.com>

I am attempting to convert my program to byte code using

perlcc -b -o np.o np.p

which appears to work fine. The problem that I am seeing is that when I
run the bytecode generated version of the program I get the following
error messages:

# np.o
Can't locate object method "new" via package "IO::Socket::INET" at np.p
line 377, <ASM_config> line 7.
Attempt to free unreferenced scalar, <ASM_config> line 7.
Attempt to free unreferenced scalar, <ASM_config> line 7.
Attempt to free unreferenced scalar, <ASM_config> line 7.
Attempt to free unreferenced scalar, <ASM_config> line 7.
#

When I run the Perl source program it works fine. Why is it that the
bytecode gets confused on the use of the socket creation?

Here is the source line it is complaining about:

$sock = IO::Socket::INET->new(PeerAddr => "$asm_addr",
                              PeerPort => 9999,
                              Proto    => 'tcp');

Thanks for any help that might come my way!!

John

--
John Simpson





------------------------------

Date: Fri, 23 Feb 2001 14:03:34 -0600
From: Vincent Granville <vincentg@datashaping.com>
Subject: stock trading
Message-Id: <3A96C216.B928F722@datashaping.com>

If you have any Perl routine of interest to stock traders, and if you
want to publish the code, email me. I will publish interesting routines
in my newsletter.
http://www.datashaping.com/newsletter.shtml

Vincent Granville, Ph.D.
www.datashaping.com



------------------------------

Date: 16 Sep 99 21:33:47 GMT (Last modified)
From: Perl-Users-Request@ruby.oce.orst.edu (Perl-Users-Digest Admin) 
Subject: Digest Administrivia (Last modified: 16 Sep 99)
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.  

| NOTE: The mail to news gateway, and thus the ability to submit articles
| through this service to the newsgroup, has been removed. I do not have
| time to individually vet each article to make sure that someone isn't
| abusing the service, and I no longer have any desire to waste my time
| dealing with the campus admins when some fool complains to them about an
| article that has come through the gateway instead of complaining
| to the source.

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.

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 V10 Issue 345
**************************************


home help back first fref pref prev next nref lref last post