[10518] in Perl-Users-Digest

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

Perl-Users Digest, Issue: 4110 Volume: 8

daemon@ATHENA.MIT.EDU (Perl-Users Digest)
Fri Oct 30 05:06:45 1998

Date: Fri, 30 Oct 98 02:00:18 -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           Fri, 30 Oct 1998     Volume: 8 Number: 4110

Today's topics:
    Re: A perl Question (Martin Vorlaender)
    Re: ANN: "pgrep" = perl grep (Lars Gregersen)
    Re: Anything like /bin/bash -x for perl? (Mark-Jason Dominus)
    Re: Checking Input for Exactly 2 numbers (Ronald J Kimball)
    Re: Checking Input for Exactly 2 numbers (Patrick Timmins)
    Re: More Serial Port Problems <spamsux-tex@habit.com>
        Need help with grep <toto@javanet.net>
    Re: Need help with grep (Larry Rosler)
    Re: Perl & Y2K - booby trap code (Ronald J Kimball)
    Re: Perl exec can't re-write more than one arg? (Sam Holden)
    Re: Please help me - unknown script routine ... (Sam Holden)
    Re: Syntactic flexibility (was: Re: psychology of langu <laheadle@boguscs.uchicago.edu>
    Re: Syntactic flexibility (was: Re: psychology of langu <dgris@rand.dimensional.com>
    Re: system() function on PERL for Win32 <r_larsen@image.dk>
    Re: system() function on PERL for Win32 (Ethan H. Poole)
    Re: Testing for number of occurances (Ronald J Kimball)
    Re: Testing for number of occurances (Craig Berry)
    Re: Using Perl CGI to generate ASP? <msergeant@ndirect.co.uk_NOSPAM>
    Re: Very Large DBM file: Finding Number of keys (Mark-Jason Dominus)
    Re: Very Large DBM file: Finding Number of keys (Larry Rosler)
    Re: Very Large DBM file: Finding Number of keys (Mark-Jason Dominus)
    Re: Very Large DBM file: Finding Number of keys (Ronald J Kimball)
    Re: Very Large DBM file: Finding Number of keys (Larry Rosler)
        Special: Digest Administrivia (Last modified: 12 Mar 98 (Perl-Users-Digest Admin)

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

Date: Fri, 30 Oct 1998 06:22:59 +0100
From: martin@RADIOGAGA.HARZ.DE (Martin Vorlaender)
Subject: Re: A perl Question
Message-Id: <36394d33.524144494f47414741@radiogaga.harz.de>

shienh gurpreet (gss2@roogna.eng.wayne.edu) wrote:
: [...]
: The problem that I'm having is that when I enter the password on my
: webpage,it says "Document Contains No Data".
: [...]
:
: print "content-type:text/html\n\n";
                      ^ There must be a space after the colon

Consider using CGI.pm. It sees to such things.

cu,
  Martin
--
                        | Martin Vorlaender | VMS & WNT programmer
 VMS is today what      | work: mv@pdv-systeme.de
 Microsoft wants        |       http://www.pdv-systeme.de/users/martinv/
 Windows NT 8.0 to be!  | home: martin@radiogaga.harz.de


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

Date: Fri, 30 Oct 1998 09:16:00 GMT
From: lg@kt.dtu.dk (Lars Gregersen)
Subject: Re: ANN: "pgrep" = perl grep
Message-Id: <363982c8.3251889@news.dtu.dk>

On 29 Oct 1998 14:43:43 GMT, sb@engelschall.com (Steffen Beyer) wrote:

>                          =======================
>                            "pgrep" - perl grep
>                          =======================
>
>Did you ever want to have a "grep" combined with the power of Perl's
>regular expressions?

Yes, I did. Many version of perl+grep do exist. Including the
search.pl script that comes with perl.

My own version of perl+grep is a perl+find+grep that greps in current
directory and in subdirectories.

It is called findgrep and can be found at
http://www.gbar.dtu.dk/~matlg/findgrep/

Suggestions for improvements are welcome.

   Regards

    Lars Gregersen  

Lars Gregersen, M.Sc. Chem. Engng.
Department of Chemical Engineering, DTU, Denmark
E-mail:   lg@kt.dtu.dk
Homepage: http://www.gbar.dtu.dk/~matlg/


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

Date: 30 Oct 1998 00:47:41 -0500
From: mjd@op.net (Mark-Jason Dominus)
Subject: Re: Anything like /bin/bash -x for perl?
Message-Id: <71bjtt$6em$1@monet.op.net>

In article <ysiz7lxjw18w.fsf@nunki.usc.edu>,
tbrannon  <brannon@lnc.usc.edu> wrote:
>
>I would like for each line of my Perl program to to printed to stdout
>just prior to execution.

http://www.plover.com/~mjd/perl/Trace/

>Please advise on the methods to achieve this.

Tad's method is probably more useful.



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

Date: Fri, 30 Oct 1998 00:50:27 -0500
From: rjk@coos.dartmouth.edu (Ronald J Kimball)
Subject: Re: Checking Input for Exactly 2 numbers
Message-Id: <1dhoqkv.18emkpxazva2N@bay1-402.quincy.ziplink.net>

Martien Verbruggen <mgjv@comdyn.com.au> wrote:

> In article <1dhmuv8.1rlm5ki9mzchcN@bay1-214.quincy.ziplink.net>,
>   rjk@coos.dartmouth.edu (Ronald J Kimball) writes:

> >> How would you check the input then to make sure it has exactly two
> >> numbers inputed. Not more not less.
> > 
> > 2 == (() = /\d+/g);
> 
> Are you sure you want that '+' in there?

Yes, I am.

Two digits: 12

Two numbers: 12 34


If I just wanted to count digits, I would have used tr/0-9//.

-- 
 _ / '  _      /         - aka -         rjk@coos.dartmouth.edu
( /)//)//)(//)/(     Ronald J Kimball      chipmunk@m-net.arbornet.org
    /                                  http://www.ziplink.net/~rjk/
        "It's funny 'cause it's true ... and vice versa."


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

Date: Fri, 30 Oct 1998 06:42:44 GMT
From: ptimmins@netserv.unmc.edu (Patrick Timmins)
Subject: Re: Checking Input for Exactly 2 numbers
Message-Id: <71bn54$gt4$1@nnrp1.dejanews.com>

In article <36390B8B.579E55F2@fccj.org>,
  bill@astro.fccj.org wrote:

> > Mike <support@counter.w-dt.com> wrote:
> >
> > > How would you check the input then to make sure it has exactly two
> > > numbers inputed. Not more not less.
[snip]
> What about -
>
> unless ($number =~ /(\d+)/ && /^[1-99]$/) {
>     print "Number entered not numeric or greater than 99...\n\n";
>     exit;
> }

/(\d+)/ will match anything that has one or more consecutive
digits in it: eg: 3, 99, AK47, "4 Wheel Drive", etc (and you don't
need the parentheses).

/^[1-99]$/ will match any single digit, 1 to 9 ... the brackets '[]'
are a character class, in which you've included the digits 1 to 9 with
the 1-9, and then you've put in another 9, which has no effect, since
you already have a nine in the character class. Since there is no
quantifier on the character class, and since you've anchored it front
and back with the ^ and $, you must have one and only one element from
the character class (ie a digit from 1 to 9) for the whole of your
target string. Doubly wrong here is that your not even using $number
as your target string for this regex, but $_ instead.

Regexes are a complete language in themselves, and while all of the
information for them *is* there in the perldocs, I must admit, things
did not really "kick in" for me until I read Jeffrey Friedl's
"Mastering Regular Expressions", published by O'Reilly and Assoc.
Everyone who uses Perl should own this book. It's honestly one of the
very best and most useful technical books I've ever read.

Patrick Timmins
$monger{Omaha}[0]

-----------== Posted via Deja News, The Discussion Network ==----------
http://www.dejanews.com/       Search, Read, Discuss, or Start Your Own    


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

Date: Thu, 29 Oct 1998 13:04:36 +0000
From: Austin Schutz <spamsux-tex@habit.com>
Subject: Re: More Serial Port Problems
Message-Id: <363867E4.7137@habit.com>

Peter Griessl wrote:
> 
> Use the POSIX module for setting up the communication (Camel p.469) and
> then
> read/write using sysread/syswrite and select(2). You probably want to
> read the manpages select(2), termios(3) first.
> This is a small code example for reading/writing to a modem connected to
> the
> serial port (say "AT" to the modem, receive "OK", ....).
> note: see select(2) for timeouts instead of blocking mode
> 
> #!/usr/bin/perl -w
> 
> use POSIX qw(:termios_h :fcntl_h);
> 
[Remainder of lengthy painful script snipped]

	Try this snippet bundled with the Expect module, condensed:

#!/path/to/perl

use Expect;

$device="/dev/modem" unless $device = shift(@ARGV);
open(DEVICE,"+>$device") || die "Couldn't open $device, $!\n";
# Expectize it.
$modem=Expect->exp_init(\*DEVICE);
# Let's watch the output. Once again, output isn't automatically
# watched since it was an initialized handle and not a process.
$modem->log_stdout(1);
# Put it in raw mode w/ no echoing so it will operate as expected.
$modem->exp_stty('raw','-echo');
print "Initializing modem\n";
$modem->send_slow(.5,"ATZH0\r");
$modem->expect(30,'-re','^OK\r?$')|| warn "Never got OK from modem\n";
print "Modem initialized.\n";
print "Beginning interaction, escape character is ^W.\n";
$modem->interact(\*STDIN,"\027");
# Done? Reset the modem, close the handle.
print $modem "+++";
sleep 3;
print $modem "ATZH0\r";
sleep 1;
# Grab any output ready on the handle, toss it.
$modem->expect(0);
$modem->hard_close();
__END__

	I find it easier. YMMV, of course. Most systems with a UUCP
package include 'cu' which can also be spawned via Expect. Also,
exp_stty() which uses IO::Stty() which uses POSIX::Termios() only
supports those things which are part of the POSIX standard. For other
stuff, like setting flow control, it is usually easiest to use the
system stty, as in:

$device="/dev/modem" unless $device = shift(@ARGV);
open(DEVICE,"+>$device") || die "Couldn't open $device, $!\n";
`stty ctsxon rtsxoff <$device >$device`
 .....

	See your man page for stty for more details on non-posix
tty settings. Some Unixen (Linux, for example) have stty's which will
block or otherwise exhibit unpleasant behavior when used in this manner.
Just test and see I guess.

	Austin


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

Date: Thu, 29 Oct 1998 23:11:09 -0500
From: Josh Feinblum <toto@javanet.net>
Subject: Need help with grep
Message-Id: <36393C5C.E3C6A3F2@javanet.net>

I was having some difficulties with grep and was wondering if anyone
could help.

I have a grep expression that needs to search for a pattern in an array
and contained in the pattern is a value for a future variable.  The
problem is that grep doen't seem to set $1 and I was wondering if anyone
had any ideas.
Here the small bit of code

@lines = <FILE>;
 grep {/<!-- INSERT TYPE="ADV" Value="(.*)" -->/} @lines;
$location=$1;

I have tryied everything that I could think of.  Please help
Thanks in advance
Josh



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

Date: Thu, 29 Oct 1998 21:51:27 -0800
From: lr@hpl.hp.com (Larry Rosler)
Subject: Re: Need help with grep
Message-Id: <MPG.10a2f3b595d757a59898f4@nntp.hpl.hp.com>

[Posted to comp.lang.perl.misc and copy mailed.]

In article <36393C5C.E3C6A3F2@javanet.net> on Thu, 29 Oct 1998 23:11:09 
-0500, Josh Feinblum <toto@javanet.net> says...
 ... 
> I have a grep expression that needs to search for a pattern in an array
> and contained in the pattern is a value for a future variable.  The
> problem is that grep doen't seem to set $1 and I was wondering if anyone
> had any ideas.
> Here the small bit of code
> 
> @lines = <FILE>;
>  grep {/<!-- INSERT TYPE="ADV" Value="(.*)" -->/} @lines;
> $location=$1;

You are using the wrong tool.  One indication of that is that you are 
using 'grep' in void context (that is, discarding the value it returns, 
and using it only for its side effects).  This is *never* the best way 
to express the solution.

'grep' is like the Energizer bunny.  It just keeps going and going.  Try 
the following instead:

    undef $location;
    foreach (@lines) {
        if (/<!-- INSERT TYPE="ADV" Value="(.*)" -->/) {
            $location = $1;
            last;
        }
    }
    print "$location\n" if defined $location;

You have to copy the value of $1 because it is localized to the block in 
which it is set.

-- 
(Just Another Larry) Rosler
Hewlett-Packard Laboratories
http://www.hpl.hp.com/personal/Larry_Rosler/
lr@hpl.hp.com


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

Date: Fri, 30 Oct 1998 00:50:29 -0500
From: rjk@coos.dartmouth.edu (Ronald J Kimball)
Subject: Re: Perl & Y2K - booby trap code
Message-Id: <1dhorkr.ribdj91hg25fmN@bay1-402.quincy.ziplink.net>

Uri Guttman <uri@sysarch.com> wrote:

>   LR> Command line:
> 
>   LR> perl -we '...' (correct) is not the same as perl -ew '...'
>   LR> (wrong).  In this respect, Perl command-line processing differs
>   LR> from the Unix norm, in which any number of single-letter
>   LR> no-argument options may be mixed with one single-argument option,
>   LR> in any order.
> 
> what do you mean by -e taking no argument? -e takes the next argument as
> perl code. so -ew is trying to execute 'w'.

Although this wasn't always the case...

~> perl -ew;
~> perl -w -ew
~> perl -edie
~> perl -ew 'print "hello\n"';
hello
~> perl -e'print "hello\n"' 'print "goodbye\n"'
goodbye
~> perl -v

This is perl, version 5.002 with DEBUGGING


Copyright 1987-1996, Larry Wall

Perl may be copied only under the terms of either the Artistic License
or the GNU General Public License, which may be found in the Perl 5.0
source kit.

~>


This is fixed in later versions of Perl.

-- 
 _ / '  _      /         - aka -         rjk@coos.dartmouth.edu
( /)//)//)(//)/(     Ronald J Kimball      chipmunk@m-net.arbornet.org
    /                                  http://www.ziplink.net/~rjk/
        "It's funny 'cause it's true ... and vice versa."


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

Date: 30 Oct 1998 05:41:46 GMT
From: sholden@pgrad.cs.usyd.edu.au (Sam Holden)
Subject: Re: Perl exec can't re-write more than one arg?
Message-Id: <slrn73ikcq.sbo.sholden@pgrad.cs.usyd.edu.au>

On 30 Oct 1998 05:32:29 GMT, Marco Nicosia <marco@snowbird.Berkeley.EDU> wrote:
>So, it's really cool that perl can do this:
>exec {'/bin/csh'} '-sh' ;
>and the process will show up in the process table as '-sh', I like that.
>
>What I'd really like, though is:
>exec {'/bin/sleep 60'} 'minute' ;

exec {'/bin/sleep'} 'minute', 60;

>
>... but every time I try this, perl just exits immediately, no error.
>
>Is there any way I can get around this? The reason I'm trying this is to
>open connections to several machines, and have each connection distinguishable:
>if ($pidA = fork) { 
>  if ($pidB = fork) {
>    exec {'ssh machineB huge amt of gobbledygook'} 'MachineBProc' ;
>  } else {
>    exec {'ssh machineA huge amt of gobbledygook'} 'MachineAProc' ;
>  }
>}

exec {'ssh'} 'MachineBProc', 'machineB', 'huge', 'amt', 'of', 'gobbledygook';

is what 'perldoc -f exec' would indicate...


-- 
Sam

Perl was designed to be a mess (though in the nicest of possible ways). 
	--Larry Wall


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

Date: 30 Oct 1998 05:01:02 GMT
From: sholden@pgrad.cs.usyd.edu.au (Sam Holden)
Subject: Re: Please help me - unknown script routine ...
Message-Id: <slrn73ii0e.sbo.sholden@pgrad.cs.usyd.edu.au>

On Thu, 29 Oct 1998 20:13:31 GMT, David Rummel <dave.vs@writeme.com> wrote:
>Hello,
>my name is David and I'm a novice in writing
>scripts in perl and now I have a problem, I'm
>sure it exists, but I haven't found it...
>
>What I mean is the command-sequence to
>do "POST" fromin perl-scripts.
>
>I only know the one for "GET", but I
>need the one for "POST" - it maybe is
>only a little changing?

use LWP;

along with 'perldoc LWP' of course.

Don't reinvent the wheel use the modules available  at CPAN...

-- 
Sam

It has been discovered that C++ provides a remarkable facility for
concealing the trival details of a program--such as where its bugs are.
	--David Keppel


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

Date: Fri, 30 Oct 1998 06:00:20 GMT
From: Lyn A Headley <laheadle@boguscs.uchicago.edu>
Subject: Re: Syntactic flexibility (was: Re: psychology of language choice (was Re: language war ...))
Message-Id: <wr33e86oah7.fsf@yeenoghu.cs.uchicago.edu>

ilya@math.ohio-state.edu (Ilya Zakharevich) writes:

> > no, it's a passable approximation to an interactive development
> > environment.  you have to enter all your functions on one line!
> 
> What makes you think so?
> 
> Ilya

maybe I'm missing something, but...

  DB<1> sub hello {
Missing right bracket at (eval 6) line 4, at end of line
syntax error at (eval 6) line 4, at EOF
 

-Lyn



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

Date: Fri, 30 Oct 1998 06:14:30 GMT
From: Daniel Grisinger <dgris@rand.dimensional.com>
Subject: Re: Syntactic flexibility (was: Re: psychology of language choice (was Re: language war ...))
Message-Id: <m3zpaer3kg.fsf@rand.dimensional.com>

Lyn A Headley <laheadle@boguscs.uchicago.edu> writes:

<snip perl debugger only works on single lines>

> maybe I'm missing something, but...
> 
>   DB<1> sub hello {
> Missing right bracket at (eval 6) line 4, at end of line
> syntax error at (eval 6) line 4, at EOF

$perl -de8

Loading DB routines from perl5db.pl version 1.0401
Emacs support available.

Enter h or `h h' for help.

main::(-e:1):	8
  DB<1> sub hello {                            \
  cont:     print qq.Hello, world\n.;          \
  cont: }

  DB<2> hello
Hello, world

  DB<3> 

dgris
-- 
Daniel Grisinger              dgris@rand.dimensional.com
Supporter of grumpiness where grumpiness is due on clpm.
perl -Mre=eval -e'$_=shift;;@[=split//;;$,=qq;\n;;;print 
m;(.{$-}(?{$-++}));,q;;while$-<=@[;;' 'Just Another Perl Hacker'


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

Date: Fri, 30 Oct 1998 06:54:39 +0100
From: R. A. Larsen <r_larsen@image.dk>
Subject: Re: system() function on PERL for Win32
Message-Id: <VA.0000006e.0021315a@octo>

grahams@wpds.com wrote:
> 
> In article <36369e46.0@news.redrose.net>,
>   mprice@netconexinc.com (Mike Price) wrote:
[Mike's posting deleted]
> I'm a Perl newbie myself but I found this works quite nicely on WIN95
> platform:
> 
> #!/usr/bin/perl
> 
> $source = "junk";
> $sink   = "more_junk";
> $status = system("copy $source $sink");
> #
> # I know you unix users would like to see this but I couldn't get it to work!
> # or die "couldn't execute system command: $!\n";
> #

>From the first page returned by perldoc -f system :

[cut]
 @args = ("command", "arg1", "arg2");
 system(@args) == 0
      or die "system @args failed: $?"
[cut]

Most of the function calls return zero if they fail BUT system() return zero if it 
succeds!

> if ($status) {
>     print "couldn't execute system: $status\n";
> }

And that is exactly what you are testing for here.

I hope this helps.

Reni
-- 
Using Virtual Access
http://www.vamail.com



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

Date: Fri, 30 Oct 1998 07:10:32 GMT
From: ehpoole@ingress.com (Ethan H. Poole)
Subject: Re: system() function on PERL for Win32
Message-Id: <IDd_1.2504$Qf3.4589@news9.ispnews.com>

[Posted and Emailed]  In article <VA.0000006e.0021315a@octo>, 
r_larsen@image.dk says...

>Most of the function calls return zero if they fail BUT system() return zero 
>if it succeds!

Although this will usually work, it does not work for the reason you suggest.

system() returns the exit status of the application you launched.  This is 
customarily zero for success, but the application programmer could easily set 
this to most anything else if they wish.

-- 
Ethan H. Poole              | Website Design and Hosting,
                            | CGI Programming (Perl & C)..
========Personal=========== | ============================
* ehpoole @ ingress . com * | --Interact2Day--
http://home1.gte.net/ehp/   | http://www.interact2day.com/



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

Date: Fri, 30 Oct 1998 00:50:30 -0500
From: rjk@coos.dartmouth.edu (Ronald J Kimball)
Subject: Re: Testing for number of occurances
Message-Id: <1dhosi8.1eif7qy10kas6pN@bay1-402.quincy.ziplink.net>

Uri Guttman <uri@fastengines.com> wrote:

> but this is counting a single char which you know you can do with
> tr///. your problem was full patterns which you wanted to do with a
> scalar m//g and no loop. 

It's not that big a cognitive leap from counting occurences of a single
char, which you can do with tr///, to counting occurences of a fixed
multi-chararcter substring, which you cannot do with tr///.

$count = () = m/camel/;  # how many times does camel occur in $_ ?

Obviously you don't need to save the actual matches, because they'll all
be 'camel'.

-- 
 _ / '  _      /         - aka -         rjk@coos.dartmouth.edu
( /)//)//)(//)/(     Ronald J Kimball      chipmunk@m-net.arbornet.org
    /                                  http://www.ziplink.net/~rjk/
        "It's funny 'cause it's true ... and vice versa."


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

Date: 30 Oct 1998 07:11:32 GMT
From: cberry@cinenet.net (Craig Berry)
Subject: Re: Testing for number of occurances
Message-Id: <71bor4$6ub$1@marina.cinenet.net>

Ronald J Kimball (rjk@coos.dartmouth.edu) wrote:
: $count = () = m/camel/;  # how many times does camel occur in $_ ?
                        ^ Need /g option

---------------------------------------------------------------------
   |   Craig Berry - cberry@cinenet.net
 --*--    Home Page: http://www.cinenet.net/users/cberry/home.html
   |      "Ripple in still water, when there is no pebble tossed,
       nor wind to blow..."


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

Date: Fri, 30 Oct 1998 09:40:33 +0000
From: Matt Sergeant <msergeant@ndirect.co.uk_NOSPAM>
Subject: Re: Using Perl CGI to generate ASP?
Message-Id: <36398991.A8BC9F40@ndirect.co.uk_NOSPAM>

David Bluestein II wrote:
> 
> There was a post a long time back about using a Perl CGI script on Windows
> to generate an ASP page that was then properly processed by IIS. I tried
> putting the VBScript code in my Perl output, but it wasn't processed by
> IIS and just came out as text.
> 
> Is there something I need to do to the CGI to have IIS treat it as
> generating an ASP page that should be processed?

What you are doing sounds totally psycho - why not just use PerlScript
(it's an active scripting engine, so it runs fine with ASP).

The answer to your question is that you would have to output it to a
file and redirect the browser to that file, but then how do you delete
that file? There's no other way. The web server doesn't parse your
output to check if it's ASP (or HTML or anything else) it just sends it
to the browser.

-- 
<Matt/>

| Fastnet Software Ltd              |   Perl in Active Server Pages   |
| Perl Consultancy, Web Development |   Database Design   |    XML    |
| http://come.to/fastnet            |    Information Consolidation    |


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

Date: 30 Oct 1998 00:12:37 -0500
From: mjd@op.net (Mark-Jason Dominus)
Subject: Re: Very Large DBM file: Finding Number of keys
Message-Id: <71bhs5$67o$1@monet.op.net>

In article <yliuh2d5f8.fsf@windlord.stanford.edu>,
Russ Allbery  <rra@stanford.edu> wrote:
>Larry Rosler <lr@hpl.hp.com> writes:
>>    scalar keys %UNIQUE_IPS
>
>If you can show me where in the documentation it promises that keys
>in a scalar context won't simply build a list of all the keys and
>then count the number of elements, I'll withdraw my suggestion.  :)

Well, regardless of whether or not it says so in the manual, it
neither builds a list or count the keys for regular hashes.  And even
for tied hashes it doesn't build a list; it just counts.  I think that
more people need to know this.

Hey, everyone!  

	$n = keys %hash;

is very efficient!  It has the count precomputed and gets it instantly!

I agree with you that the code you showed is probably the best way to
accomplish what the original poster wanted.


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

Date: Thu, 29 Oct 1998 21:19:57 -0800
From: lr@hpl.hp.com (Larry Rosler)
Subject: Re: Very Large DBM file: Finding Number of keys
Message-Id: <MPG.10a2ec547c48b7ec9898f3@nntp.hpl.hp.com>

[Posted to comp.lang.perl.misc and copy mailed.]

In article <yliuh2d5f8.fsf@windlord.stanford.edu> on 29 Oct 1998 
20:44:59 -0800, Russ Allbery <rra@stanford.edu> says...
> Larry Rosler <lr@hpl.hp.com> writes:
> > Russ Allbery <rra@stanford.edu> says...
> 
> >> Well, this is more a work-around than an alternate solution, but I'd
> >> do:
> 
> >>         if (++$UNIQUE_IPS{$ip} == 1) {
> >>             $UNIQUE_IPS{TOTAL}++;
> >>         }
> 
> >> and then just look at $UNIQUE_IPS{TOTAL} for the total number of unique
> >> IPs seen so far.
> 
> > Er, Russ, you seem to have forgotten about
> 
> >    scalar keys %UNIQUE_IPS
> 
> No, I didn't.  If you can show me where in the documentation it promises
> that keys in a scalar context won't simply build a list of all the keys
> and then count the number of elements, I'll withdraw my suggestion.  :)
> 
> (I did check perlfunc, and I don't see a promise of that sort.)

Will the following do?  It's not 'documentation' but it is from a rather 
knowledgeable source, IMO.

http://x6.dejanews.com/getdoc.xp?AN=350453264&CONTEXT=909724487.12281475
8&hitnum=2

Re: Computing length of hash  more options  
  
Author:   Mark-Jason Dominus 
Email: mjd@op.net 
Date: 1998/05/05 
Forums: comp.lang.perl.misc  
 
In article <354EB877.8354265@ubs.com>,
Ian Maloney  <ian.maloney@ubs.com> wrote:
>In the Camel book (p.183) the recommended way to get the length of a
>hash is with:
>
>scalar keys %hash;
>
>My guess is that this is quite 'expensive' as it has to first build the
>list of keys,

Your guess is wrong.  You forgot the Rule:

	Just because you know what some function does in array context
	doesn't mean you know what it will do in scalar context.

In particular, it does not build a list of keys.

For tied hashes, it has to iterate over the keys to count them, but it
still doesn't build a list.  For regular hashes, it just goes to the
place in the hash structure where it was keeping track of the number
of entries, and returns the number.

>My question is: am I correct in thinking that this is an expensive
>operation? 

No.  For regular hashes, it will probably take about as long as
accessing a scalar variable.

> and is there an alternative?

No.

-- 
(Just Another Larry) Rosler
Hewlett-Packard Laboratories
http://www.hpl.hp.com/personal/Larry_Rosler/
lr@hpl.hp.com


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

Date: 30 Oct 1998 00:43:04 -0500
From: mjd@op.net (Mark-Jason Dominus)
Subject: Re: Very Large DBM file: Finding Number of keys
Message-Id: <71bjl8$6cr$1@monet.op.net>

In article <71bhs5$67o$1@monet.op.net>, Mark-Jason Dominus <mjd@op.net> wrote:
>I agree with you that the code you showed is probably the best way to
>accomplish what the original poster wanted.

This message was beamed into my mind by malevolent aliens from outer space.

Using `keys' is the way to go.






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

Date: Fri, 30 Oct 1998 00:50:31 -0500
From: rjk@coos.dartmouth.edu (Ronald J Kimball)
Subject: Re: Very Large DBM file: Finding Number of keys
Message-Id: <1dhosmo.18v4ldup07o4iN@bay1-402.quincy.ziplink.net>

Larry Rosler <lr@hpl.hp.com> wrote:

> [Posted to comp.lang.perl.misc and copy mailed.]
> 
> In article <yl90hyg3tt.fsf@windlord.stanford.edu> on 29 Oct 1998 
> 18:51:10 -0800, Russ Allbery <rra@stanford.edu> says...
> > Bob Stewart <rstewart@vmirror.com> writes:
> ... 
> > > And my second question, is there a way of determining the number of keys
> > > in an associative array without using the keys funtion?
> > 
> > Well, this is more a work-around than an alternate solution, but I'd do:
> > 
> >         if (++$UNIQUE_IPS{$ip} == 1) {
> >             $UNIQUE_IPS{TOTAL}++;
> >         }
> > 
> > and then just look at $UNIQUE_IPS{TOTAL} for the total number of unique
> > IPs seen so far.
> 
> Er, Russ, you seem to have forgotten about
> 
>    scalar keys %UNIQUE_IPS

Actually, Larry, I don't think he did...

First, reread the original poster's question, quoted above.  Note the
phrase 'without using the keys function'.  :-)

Second, read the following excerpt from the Blue Camel (pg 182), which
explains the justification for the original posters aversion to using
the keys function.

  In a scalar context, keys returns the number of elements of the hash
  (and resets the each iterator).  However, to get this information for
  tied hashes, including DBM files, Perl must still walk the entire
  hash, so it's not very efficient in that case.

-- 
 _ / '  _      /         - aka -         rjk@coos.dartmouth.edu
( /)//)//)(//)/(     Ronald J Kimball      chipmunk@m-net.arbornet.org
    /                                  http://www.ziplink.net/~rjk/
        "It's funny 'cause it's true ... and vice versa."


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

Date: Thu, 29 Oct 1998 22:30:28 -0800
From: lr@hpl.hp.com (Larry Rosler)
Subject: Re: Very Large DBM file: Finding Number of keys
Message-Id: <MPG.10a2fce3349edc659898f6@nntp.hpl.hp.com>

[Posted to comp.lang.perl.misc and copy mailed.]

In article <1dhosmo.18v4ldup07o4iN@bay1-402.quincy.ziplink.net> on Fri, 
30 Oct 1998 00:50:31 -0500, Ronald J Kimball <rjk@coos.dartmouth.edu> 
says...
> Larry Rosler <lr@hpl.hp.com> wrote:
 ...
> > Er, Russ, you seem to have forgotten about
> > 
> >    scalar keys %UNIQUE_IPS
> 
> Actually, Larry, I don't think he did...
> 
> First, reread the original poster's question, quoted above.  Note the
> phrase 'without using the keys function'.  :-)

I don't think he had religious scruples about the keys function, just 
misplaced concern about its efficiency.  Read his next sentence:

>> The FAQ says to use the keys function, but that's a killer when you
>> have hauge number of records. 
 
> Second, read the following excerpt from the Blue Camel (pg 182), which
> explains the justification for the original posters aversion to using
> the keys function.
> 
>   In a scalar context, keys returns the number of elements of the hash
>   (and resets the each iterator).  However, to get this information for
>   tied hashes, including DBM files, Perl must still walk the entire
>   hash, so it's not very efficient in that case.

I think MJD has dealt with these concerns, once directly and once by 
proxy. 

-- 
(Just Another Larry) Rosler
Hewlett-Packard Laboratories
http://www.hpl.hp.com/personal/Larry_Rosler/
lr@hpl.hp.com


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

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 4110
**************************************

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