[18961] in Perl-Users-Digest

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

Perl-Users Digest, Issue: 1156 Volume: 10

daemon@ATHENA.MIT.EDU (Perl-Users Digest)
Tue Jun 19 03:08:49 2001

Date: Tue, 19 Jun 2001 00:05:09 -0700 (PDT)
From: Perl-Users Digest <Perl-Users-Request@ruby.OCE.ORST.EDU>
To: Perl-Users@ruby.OCE.ORST.EDU (Perl-Users Digest)
Message-Id: <992934308-v10-i1156@ruby.oce.orst.edu>
Content-Type: text

Perl-Users Digest           Tue, 19 Jun 2001     Volume: 10 Number: 1156

Today's topics:
    Re: 2 questions about flock (Garry Williams)
    Re: A question on some basic things <khchan2@csis.hku.hk>
    Re: A question on some basic things <pne-news-20010618@newton.digitalspace.net>
    Re: Access C String Pointers? <rob@punketc.com>
        Can't locate Fcntl.pm in @INC <rx@rxlist.com>
        connectivity problem using ADO <sparky@suba.com>
    Re: FAQ 8.20:   How can I call my system's unique C fun <goldbb2@earthlink.net>
    Re: File::Find skips the leaf nodes in a directory tree <goldbb2@earthlink.net>
    Re: finding a file in a directory?? <goldbb2@earthlink.net>
    Re: finding a file in a directory?? <pne-news-20010619@newton.digitalspace.net>
    Re: help with regexp? <goldbb2@earthlink.net>
    Re: help with the perl scripts <goldbb2@earthlink.net>
    Re: help with the perl scripts (Chris Fedde)
    Re: MAJOR perl bug (Kenneth Graves)
    Re: matching a list with a regex <goldbb2@earthlink.net>
    Re: matching a list with a regex <krahnj@acm.org>
    Re: Mix JS variables - David Eff.. (David Efflandt)
        multiple file upload <ixanthi@ixanthi.gr>
        parsing log file <emailkevin@charter.net>
    Re: parsing log file <tony_curtis32@yahoo.com>
    Re: parsing log file (Chris Fedde)
    Re: Performance Advice: CGI servers files <goldbb2@earthlink.net>
    Re: Performance Advice: CGI servers files (Dave Bailey)
    Re: Performance Advice: CGI servers files (Chris Fedde)
        tee revisited: dup STDOUT to a file but still get outpu <johnlin@chttl.com.tw>
    Re: tee revisited: dup STDOUT to a file but still get o <goldbb2@earthlink.net>
    Re: tee revisited: dup STDOUT to a file but still get o <johnlin@chttl.com.tw>
        Digest Administrivia (Last modified: 6 Apr 01) (Perl-Users-Digest Admin)

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

Date: Tue, 19 Jun 2001 02:43:19 GMT
From: garry@ifr.zvolve.net (Garry Williams)
Subject: Re: 2 questions about flock
Message-Id: <slrn9itf27.j8a.garry@zfw.zvolve.net>

On Fri, 15 Jun 2001 11:55:33 +0100, Mark Grimshaw
<m.grimshaw@salford.ac.uk> wrote:

> I'm curious why strict would not complain if I attempted to call an
> undefined method sync() as I originally did.

This has nothing to do with `strict'.  It's a run-time exception no
matter what: 

  $ perl -we 'package A; sub new{return bless{}}package main;' \
        -e 'my $x=A->new;$x->nope'
  Can't locate object method "nope" via package "A" (perhaps you forgot
  to load "A"?) at -e line 2.

-- 
Garry Williams


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

Date: Tue, 19 Jun 2001 08:40:58 +0800
From: Bernard Chan <khchan2@csis.hku.hk>
Subject: Re: A question on some basic things
Message-Id: <3B2E9F9A.7000708@csis.hku.hk>

Your reply is helpful, but I consider it a little bit
not convincing.

The reason I ask the question here because Tom
Christiansen (hope I haven't mispelled his name) who
wrote the perl manpages insist so.

Your Perl script essentially does nothing and exits, and
the C/C++ script is an infinite loop. I think actually it
is you that have been comparing onions and apples.
I suppose most people would be interested in comparing
two programs that functionally are the same.

Yet it is true that good compiler or interpreter designs
allow a series of operations to be carried out to optimize
the performance of the executable. Bad compilers can result
in sluggish exes.

Thank you again for your answer.
===============
Bernard Chan


Philip Newton wrote:

> Not always.
> 
> This perl script:
> 
>     #!/usr/bin/perl
>     exit;
> 
> should finish faster than this C program after it's compiled:
> 
>     int main(void) { while(1); return 0; }
> 
> You're comparing apples with onions. And you can't even compare, say, a
> C interpreter with a C compiler since the difference depends not only on
> "compiled vs interpreted" but also, for example, on the quality of the
> compiler or interpreter (as is seen by the fact that some compilers are
> considered "better" than others).
> 
> cheers,
> Philip



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

Date: Tue, 19 Jun 2001 08:26:59 +0200
From: Philip Newton <pne-news-20010618@newton.digitalspace.net>
Subject: Re: A question on some basic things
Message-Id: <51stito0csm3e77tt9r9esgjcb9a0ttb03@4ax.com>

On Tue, 19 Jun 2001 08:40:58 +0800, Bernard Chan <khchan2@csis.hku.hk>
wrote:

> I suppose most people would be interested in comparing
> two programs that functionally are the same.

Even that is difficult, since it depends also, for example, on the
algorithm.

So if you have an interpreted program sorting data with something like
quicksort, and a compiled program using bubble sort, then both programs
will "do the same thing" (the output will be sorted), but the
interpreted program may finish faster due to the better algorithm.

(Hence the frequently repeated advice not to micro-optimise first, at
least, not unless you've looked at the possibility of improving your
algorithm, for example, turning an O(n^2) algorithm into an O(n log n)
one or whatever.

Cheers,
Philip
-- 
Philip Newton <nospam.newton@gmx.li>
Yes, that really is my address; no need to remove anything to reply.
If you're not part of the solution, you're part of the precipitate.


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

Date: Tue, 19 Jun 2001 02:52:01 GMT
From: Rob Perelman <rob@punketc.com>
Subject: Re: Access C String Pointers?
Message-Id: <3B2EBE32.D4F95E9@punketc.com>

Bart Lateur wrote:
> 
> pack/unpack with template 'P' should be a start. I don't know for sure.

Tried that...if I do a pack, I get some crazy string in return.  If I do
an unpack, the program bombs.

> Anyway, you ought to be able to *copy* the C string into a perl string,
> with an API call (the equivalent to C's strcpy). The function name is
> "RTLMoveMemory", it's in KERNEL32, and the parameters are sourcepointer
> (your number, 'N'), destpointer (a prefilled perl scalar as buffer,
> 'P'), and number of bytes ('N'). Try something along the lines of:
> 
>         my $CopyMemory = new Win32::API("KERNEL32", "RTLMoveMemory",
>           [qw(N P N)], 'V');
>         my $buffer = "\0" x 1025;
>         CopyMemory->Call($file, $buffer, 1024);
>         print unpack "Z", $buffer;
> 
> Untested code, though.

It got me going in the right direction...though I had to change RTL...
to Rtl... for it to work.  But I'm getting an empty string back, and I
don't know if that's due to something I'm doing wrong, or because
Winamp's API is wrong.  I'm guessing the former.  Here's the code in
question, and I'm getting a blank string:

    $index = Win32::GUI::SendMessage($handle, WM_USER, 0, 125);
    $file =  Win32::GUI::SendMessage($handle, WM_USER, $index, 211);
    $copy = new Win32::API('KERNEL32', 'RtlMoveMemory', [qw(N P N)],
'V');
    $buffer = "\0" x 1025;
    $copy->Call($file, $buffer, 1024);
    print '-', unpack("Z*", $buffer), '-';

Any more ideas?

--
 Rob Perelman :: rob@punketc.com
  LPT1:Presents :: http://www.lpt1.org
   Alphabet Records :: http://www.alphabetrecords.com
    Punk, Etc. [Web Construction] :: http://www.punketc.com


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

Date: Mon, 18 Jun 2001 22:27:04 -0700
From: Neil Sandow <rx@rxlist.com>
Subject: Can't locate Fcntl.pm in @INC
Message-Id: <3B2EE2A8.F8B1B0EB@rxlist.com>

I'm getting the following error on a new script:

Can't locate Fcntl.pm in @INC (@INC contains:
/usr/libdata/perl/5.00503/mach /usr/libdata/perl/5.00503
/usr/local/lib/perl5/site_perl/5.005/i386-freebsd
/usr/local/lib/perl5/site_perl/5.005 .) at
/usr/home/rxlist/public_html/rxboard/webbbs_basic.pl line 192.
BEGIN failed--compilation aborted at
/usr/home/rxlist/public_html/rxboard/webbbs_basic.pl line 192.


my perl is:  This is perl, version 5.005_03 built for i386-freebsd

Copyright 1987-1999, Larry Wall

I'm trying to use an upgraded script (Webbbs) and get this error when I
run it.

-ns
---------------------------
Neil Sandow, Pharm.D.
Vice President of Pharmacy
HealthCentral.com, Inc.
rx@rxlist.com




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

Date: Tue, 19 Jun 2001 03:53:23 GMT
From: sparkane <sparky@suba.com>
Subject: connectivity problem using ADO
Message-Id: <MPG.159888b9a8be0bb8989682@news-central.giganews.com>

Hi. I'm a perl beginner trying to resolve a simple connecting to an 
access database problem. I'm not sure this is ng is appropriate for this 
question. If anyone can help me and the ng is not the appropriate forum, 
I would appreciate it if you could email me directly. Otherwise, if 
anyone here could rule out that the problem stems from my perl code 
rather than my ignorance of ADO, that would also be helpful. TIA.

sparkane

ps just so it's clear, the error occurs on the $conn->Open() line.


> Hi. I'm having a frustrating time trying to connect to an MS Access 
> database. I'm just starting to learn perl, and I think my real problem 
> here may be an ADO problem; however, I've written this script to 
> work in VB, so you be the judge.
> 
> It's pretty simple. Here's the script:
> 
> 
> use OLE;
> $conn = CreateObject OLE "ADODB.Connection" || 
> 	die "Create Object: ".Win32::OLE->LastError();
> my $path = 'Data Source=F:\ERD\LADatabase.mdb;';
> my $sys = 'jet oledb:system database=d:\Program Files\Microsoft Office\Office\system.mdw';
> my $driver = 'Provider=Microsoft.Jet.OLEDB.4.0;';
> my $connstring = $driver.$path.$sys;
> $conn->{'ConnectionString'} = $connstring;
> $conn->Open() || 
> 	die "Couldn't open connection: ".Win32::OLE->LastError();
> my $sql = "SELECT * FROM State";
> $rs = $conn->Execute($sql) || 
> 	die "Couldn't execute: ".Win32::OLE->LastError();
> while(!$rs->{EOF}) {
> 	my $stabbv = $rs->Fields('State Abbreviation')->Value;
> 	my $reg = $rs->Fields('Region')->Value;
> 	my $ncreif = $rs->Fields('NCREIF Region')->Value;
> 	write;
> 	$rs->MoveNext;
> }
> $rs->Close();
> $conn->Close();
> 
> And here's the error message:
> 
> Couldn't open connection: 0 at f:\projects\learnperl.dbtest_ado.pls 
> line 9.
> 
> I have tried this using	 only the path parameter.
> I have tried this using the path parameter, the UID parameter, and 
> the PWD parameter.
> I have tried this leaving off the sysfile parameter, for all the good it 
> would do me.
> I have referred to various and sundry help pages looking for a clear 
> explanation of how to connect to an Access database. In MS' own 
> ado doc/sdk file, which I downloaded, there is an example of a 
> connection to an Access db using exactly the parameters I have 
> used above. According to that file, you do not need to use the UID 
> and PWD parameters because the Access sysfile will default to 
> Admin and "", as one would expect.
> Anyway I'm pretty damn frustrated, and will be very grateful for a 
> little illumination on my own personal highway to hell. Thank you 
> and have a nice day.
> 
> sparkane


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

Date: Mon, 18 Jun 2001 22:20:21 -0400
From: Benjamin Goldberg <goldbb2@earthlink.net>
Subject: Re: FAQ 8.20:   How can I call my system's unique C functions from Perl?
Message-Id: <3B2EB6E5.50D2B0FB@earthlink.net>

PerlFAQ Server wrote:
> +
>   How can I call my system's unique C functions from Perl?
> 
>     In most cases, you write an external module to do it--see the answer to
>     "Where can I learn about linking C with Perl? [h2xs, xsubpp]". However,
>     if the function is a system call, and your system supports syscall(),
>     you can use the syscall function (documented in the perlfunc manpage).
> 
>     Remember to check the modules that came with your distribution, and CPAN
>     as well--someone may already have written a module to do it.
> 
> -

This FAQ should also contain a mention of the Inline::C module.

-- 
The longer a man is wrong, the surer he is that he's right.


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

Date: Tue, 19 Jun 2001 00:49:15 -0400
From: Benjamin Goldberg <goldbb2@earthlink.net>
Subject: Re: File::Find skips the leaf nodes in a directory tree?
Message-Id: <3B2ED9CB.C8B6E237@earthlink.net>

Ren Maddox wrote:
> 
> [Jeopardectomy]
> 
> On 18 Jun 2001, jonchang@my-deja.com wrote:
> 
> >> jon chang wrote:
> >> >
> >> > Hi,
> >> >
> >> > I'm trying to write a small script that'd scan a directory
> >> > recursively and create a blank index.html in each subdirectory
> >> > where no index.html, index.htm, or index.cgi is found.
> >> >
> >> > I found the following script skipping the leaf nodes of a
> >> > directory. Any help would be appreciated.
> >> >
> >> > Also, is there a better way of doing things below in Perl,
> >> > instead of invoking system() call.
> >> >
> >> > Regards.
> >> >
> >> > #!/usr/local/bin/perl -w
> >> >
> >> > use File::Find;
> >> > @ARGV = ('.') unless @ARGV;
> >> > find sub {
> >> >    if ( !(-e 'index.cgi' || -e 'index.html' || -e 'index.htm') )
> >> >    { system("touch index.html; chown www:www index.html; chmod
> >> >    644 index.html")
> >> > ;
> >> >    }
> >> > }, @ARGV;
> >>
> > Thanks to both the people who replied with their
> > scripts. Unfortunately, they too don't take care of the leaf
> > directories if they are empty.  Perhaps some File::Find experts need
> > to look into this.
> 
> The problem you're running into is hard for me to describe, but
> basically, you are expecting the current directory to be each
> subdirectory in turn.  However, the current directory is only set when
> a *file* is being examined.
> 
> What you really want to do is look at *directories*, not files, and
> then look inside the directory.
> 
> #!/usr/bin/perl
> use strict;
> use warnings;
> use File::Find;
> @ARGV = "." unless @ARGV;
> find sub {
>   -d || return;  # only care about directories
>   unless ( -e "$File::Find::name/index.cgi" ||
>            -e "$File::Find::name/index.html" ||
>            -e "$File::Find::name/index.htm" ) {
>     my $file = "$File::Find::name/index.html";
>     my $fh;
>     open $fh, ">", $file
>       and close $fh
>         or warn "Could not create $file, $!\n";
>     my $uid = getpwnam "www";
>     my $gid = getgrnam "www";
>     chown $uid, $gid, $file;
>     chmod 0644, $file;
>   }
> }, @ARGV;
> __END__

Is there a reason for having
	unless( -e .... ) {
instead of
	return unless( -e .... );
Is there a reason for using $File::Find::name instead of $_ ?  Keep in
mind that find() has chdir()ed into the parent dir of $_ before the
wanted sub is called.  Is there a reason for doing an explicit close on
the filehandle?  It is after all stored in a lexical, and will
automatically close at the end of the scope.  Do you expect uid and gid
of www to change at any time during the execution of the program?  Why
not stick those assignments up outside of the sub?

-- 
The longer a man is wrong, the surer he is that he's right.


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

Date: Tue, 19 Jun 2001 01:24:14 -0400
From: Benjamin Goldberg <goldbb2@earthlink.net>
Subject: Re: finding a file in a directory??
Message-Id: <3B2EE1FE.974D338@earthlink.net>

Philip Newton wrote:
[snip]
>     opendir DIR, '.' or die "Can't opendir '.': $!";
>     my @files = map  { $_->[1] }
>                 sort { $a->[0] <=> $b->[0] }
>                 map  { [ (stat($_))[9], $_ ] }
>                 grep { /^what\..*\.4Jun\./s }
>                 readdir DIR;
>     closedir DIR or die "Can't closedir '.': $!";

Guttman-Rosler Transform is usually faster than Schwartzian transform.

    my @files = map { substr $_, 4 } sort
		map { pack "N a*", (stat($_))[9], $_ }
		grep { /^what\..*\.4Jun\./s }
		readdir DIR;

-- 
The longer a man is wrong, the surer he is that he's right.


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

Date: Tue, 19 Jun 2001 08:28:21 +0200
From: Philip Newton <pne-news-20010619@newton.digitalspace.net>
Subject: Re: finding a file in a directory??
Message-Id: <m6stit0f1skeeu92vtaglel9ua1u3vpek5@4ax.com>

On Tue, 19 Jun 2001 01:24:14 -0400, Benjamin Goldberg
<goldbb2@earthlink.net> wrote:

> Guttman-Rosler Transform is usually faster than Schwartzian transform.

Fair enough.

>     my @files = map { substr $_, 4 } sort

I think you should have moved 'sort' to a line of itself, though,
otherwise it kind of gets lost at the end of the line.

Cheers,
Philip
-- 
Philip Newton <nospam.newton@gmx.li>
Yes, that really is my address; no need to remove anything to reply.
If you're not part of the solution, you're part of the precipitate.


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

Date: Tue, 19 Jun 2001 01:10:36 -0400
From: Benjamin Goldberg <goldbb2@earthlink.net>
Subject: Re: help with regexp?
Message-Id: <3B2EDECC.45A8A5BF@earthlink.net>

Dave Bailey wrote:
> 
> On Sun, 17 Jun 2001 19:29:28 -0400, Benjamin Goldberg
> <goldbb2@earthlink.net> wrote:
> >oza wrote:
> [...]
> >> I will use Apaches rewrite module to translate the url in first
> >> line to the one in second line below:
> >>
> >> www.mysite.com/top/scriptname/modename/idnum
> >> www.mysite.com/scriptname.php?mode=modename&id=idnum
> [...]
> >I don't see why you *want* to rewrite the urls like this, though.  It
> >is entirely possible to use a cgi with a url like the following:
> >       http://host/path/foo.cgi/param/param
> >
> >The path_info function/method of CGI.pm will return the string
> >"/param/param", as will $ENV{PATH_INFO}.  This is, IMHO, a superior
> >way of giving static arguments to a CGI (by static, I mean part of
> >the fixed content of a page, not generated by a <form> tag).
> 
> CGI.pm is a nasty module to use if all you need is CGI arguments.
> Using CGI.pm under mod_perl increases the size of your Apache
> processes by around 2 MB compared with something simpler like
> Apache::Request, which also provides a param() method.  In any case,
> the point is moot since the OP is migrating his site's CGI content to
> PHP, not Perl.

No, the point would be moot if PHP was unable to access the PATH_INFO
environment variable.

> As for the argument scheme, it's not superior, it's just different.
> In some situations the CGI arguments have a natural hierarchy such
> as /chapter/section/paragraph which lends itself nicely to directory
> style naming.  In other situations this is not the case, such as
> ?x=14&y=7&z=5.  Which one is more suitable depends on what the
> arguments represent, IMHO.

True.  But, for for *most* static content, path_info is better, IMHO. 
For example, if an ordinary [non cgi-generated] html file were
referencing a cgi with fixed xyz, I would probably prefer something like
"/14/7/5" to "?x=14&y=7&z=5".  It's kinda like the difference between
using $cgi->header("text/html") and $cgi->header(-TYPE=>"text/html").

-- 
The longer a man is wrong, the surer he is that he's right.


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

Date: Tue, 19 Jun 2001 00:11:37 -0400
From: Benjamin Goldberg <goldbb2@earthlink.net>
Subject: Re: help with the perl scripts
Message-Id: <3B2ED0F9.E43DB3E6@earthlink.net>

u518615722@spawnkill.ip-mobilphone.net wrote:
> 
> We need to run the following scripts to change phone #s once a while.
> 
> perl -pi.bak -e 's/string1/string2/g'
>    `find /opt2/oracle/product/ 8.1.7/dba/ -name "*" -print`

Is that space between produce/ and 8.1.7 supposed to be there?

> because we have hundreds of files and sub-directories so we can not
> change them one by one.  Sometimes somebody put a huge dmp files w/o
> let us know, so we will run out of spaces by running this scripts.
> 
> How can we make smarter that it will only make a copy of the files
> that get changed and do not make copy of those that are not changed?

One possibility is to leave off the .bak from the -i flag, and that will
do an inplace edit without making a backup.  I don't think this works on
DOS/Win, though.  If -i does work for you, ignore the following code.

This untested code opens a file, does an in-memory edit, makes a backup,
writes the new version, then deletes the backup.  If no changes are made
by the edit, no backup is made, and nothing is written to disk.  If it
encounters a failure while editing, the backup is not deleted.

#! perl -w
use strict;
use File::Find;
use File::Copy;

find sub {
	return if /\.bak$/;
	return unless !-l && -f _ && -r _ && -w _;
	
	unless( open my $fh, "+<", my $fn = $_ ) {
		warn "open(FH, +<, $File::Find::dir/$_): $!\n"
		return;
	}
	local $_ = do { local $/ = \ -s $fh; <$fh>; };
	/string1/string2/msg or return;
	unless( my $made_backup = copy( $fn, "$fn.bak" ) ) {
		warn "$File::Find::dir copy($fn,$fn.bak): $!\n";
	}
	unless ( seek( $fh, 0, 0 ) ) {
		warn "seek($File::Find::dir/$fn,0,0): $!\n";
		return;
	}
	print $fh $_; # print always succeeds, right?
	unless( truncate $fh, my $len = length $_ ) {
		warn "truncate($File::Find::dir/$fn,$len): $!\n";
		return;
	}
	if( $made_backup and not unlink( "$fn.bak" ) ) {
		warn "unlink($File::Find::dir/$fn.bak): $!\n";
	}
	# filehandle in lexical automatically closed at end of scope.
} "/opt2/oracle/product/8.1.7/dba/";
__END__

-- 
The longer a man is wrong, the surer he is that he's right.


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

Date: Tue, 19 Jun 2001 04:48:26 GMT
From: cfedde@fedde.littleton.co.us (Chris Fedde)
Subject: Re: help with the perl scripts
Message-Id: <uQAX6.151$T3.212159488@news.frii.net>

In article <l.992889174.1843963623@[198.138.198.252]>,
 <u518615722@spawnkill.ip-mobilphone.net> wrote:
>We need to run the following scripts to change phone #s once a while.
>
>perl -pi.bak -e 's/string1/string2/g' `find /opt2/oracle/product/
>8.1.7/dba/ -name "*" -print`
>
>because we have hundreds of files and sub-directories so we can not
>change them one by one.  Sometimes somebody put a huge dmp files w/o let
>us know, so we will run out of spaces by running this scripts.
>
>How can we make smarter that it will only make a copy of the files
>that get changed and do not make copy of those that are not changed?
>

Several ideas here.  One is to re-order your command line:

    find mumble | xargs perl -pi.bak frotz

This prevents you from creating command lines that are bigger than the
shell command buffer.  It also lets you be more flexible with finds
arguments.

Another is to use the '-type f' option in find.  That'll keep your code
from trying to do the substitution in directory files.

Think about a better -name pattern than "*".  Maybe there is something about
the names of the files that need to be changed so that you can avoid some
files.  Maybe a grep between the find and the perl could help too:

    find mumble | grep -v "don't care" | xargs perl -pi.bak frotz

Read about finds -prune and -newer options and experiment with them.

Consider using -i without an argument.

Just my thoughts
Good Luck
-- 
    This space intentionally left blank


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

Date: Tue, 19 Jun 2001 02:25:53 GMT
From: kag@kag.citysource.com (Kenneth Graves)
Subject: Re: MAJOR perl bug
Message-Id: <slrn9ite1f.12n.kag@kag.citysource.com>

In article <12124e47.0106181553.59c020ff@posting.google.com>, None wrote:
>$variable=@array;
>my($variable)=@array;

As others have pointed out, it's a context issue.  I like to make
things explicit when grabbing an array's length:
my $variable = scalar(@array);

Yes, it's redundant.  But when I go back to look at that code later,
its obvious to me that I was wanting to get the length of @array.
Other people prefer different code style.

Doesn't slow things down significantly.  Anyone want to explain why
Benchmark claims it's (very slightly) faster?

kag(kag):~$ perl -MBenchmark
@a=(1,2,3,4);

timethese(-10,{
	'implicit'=>'my $length = @a;',
	'explicit'=>'my $length = scalar(@a);'
});

Benchmark: running explicit, implicit, each for at least 10 CPU seconds...
  explicit:  7 wallclock secs (10.01 usr + -0.01 sys = 10.00 CPU) @ 855652.30/s
 (n=8556523)
  implicit: 11 wallclock secs (10.01 usr + -0.01 sys = 10.00 CPU) @ 853423.90/s
 (n=8534239)

(Second run)
Benchmark: running explicit, implicit, each for at least 10 CPU seconds...
  explicit: 11 wallclock secs ( 9.99 usr +  0.01 sys = 10.00 CPU) @ 856165.00/s
 (n=8561650)
  implicit:  8 wallclock secs (10.00 usr +  0.00 sys = 10.00 CPU) @ 852797.50/s
 (n=8527975)

--kag


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

Date: Mon, 18 Jun 2001 22:18:44 -0400
From: Benjamin Goldberg <goldbb2@earthlink.net>
Subject: Re: matching a list with a regex
Message-Id: <3B2EB684.4A8510C3@earthlink.net>

Bart Lateur wrote:
> 
> Is there a simple way that I'm missing, to match a string containing a
> list of items, without repeating the pattern?
> 
> For example, uppose an item can be a number or a string:
> 
>         \d+
> or
>         "[^"]*"
> 
> Items are separated by one comma, preceded with an opening paren,
> followed by a closing paren. No comma is allowed at the start or at
> the end of the list.
> 
> It should match:
> 
>         (123,"abc",10)
> or
>         (123)
> or even
>         ()
> 
> but not
>         (,123)
> or
>         (123,)
> 
> This is a working solution:
> 
>         /\((?:(?:\d+|"[^"]*")(?:,(?:\d+|"[^"]*"))*)?\)/
> 
> but the repetition of the term pattern is ugly, especially since my
> real pattern will be more complex than this. Ideally, I'd want
> something that is only half as big as this one...

	my $str  = qr/"(?:[^"]+|"")*"/;
	my $term = qr/\d+|$str/;
	my $expr = qr/\($term(?:,$term)*\)/;
	my $file = do { local $/; <DATA> };
	while( $file =~ m/^($expr)$/g ) {
		my $csv = $1;
		while( $csv =~ m/$term,?/g ) {
			if( s/^"(.*)"$/$1/s ) {
				s/""/"/g;
				process_string( $_ );
			} else {
				process_number( $_ );
			}
		}
	}

-- 
The longer a man is wrong, the surer he is that he's right.


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

Date: Tue, 19 Jun 2001 03:46:01 GMT
From: "John W. Krahn" <krahnj@acm.org>
Subject: Re: matching a list with a regex
Message-Id: <3B2ECB26.DD51BEF7@acm.org>

Bart Lateur wrote:
> 
> Is there a simple way that I'm missing, to match a string containing a
> list of items, without repeating the pattern?
> 
> For example, uppose an item can be a number or a string:
> 
>         \d+
> or
>         "[^"]*"
> 
> Items are separated by one comma, preceded with an opening paren,
> followed by a closing paren. No comma is allowed at the start or at the
> end of the list.
> 
> It should match:
> 
>         (123,"abc",10)
> or
>         (123)
> or even
>         ()
> 
> but not
>         (,123)
> or
>         (123,)
> 
> This is a working solution:
> 
>         /\((?:(?:\d+|"[^"]*")(?:,(?:\d+|"[^"]*"))*)?\)/
> 
> but the repetition of the term pattern is ugly, especially since my real
> pattern will be more complex than this. Ideally, I'd want something that
> is only half as big as this one...

How about /(?:\((?!,)|(?<!\(),)(?:\d+|"[^"]*")?(?<!,)\)/

Not much smaller but no repeating pattern.


John
-- 
use Perl;
program
fulfillment


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

Date: Tue, 19 Jun 2001 04:27:51 +0000 (UTC)
From: see-sig@from.invalid (David Efflandt)
Subject: Re: Mix JS variables - David Eff..
Message-Id: <slrn9itl67.34i.see-sig@typhoon.xnet.com>

On Mon, 18 Jun 2001, BUCK NAKED1 <dennis100@webtv.net> wrote:
> "I had already tried sprintf, double quotes, [etc]. and that didn't work
> either. Can you see any other reason why $ref is not interpolating?"
> 
> "etc" included trying it without any quotes. Now, what part of "etc" and
> "did not work" did YOU not understand, O Wise One???
> 
> Either answer the question or don't; but trying to be a wise-ass is not
> helpful.

Sorry, but I went a little further and it works even better than I though
it would, which is why I don't understand why you have a problem.  Link an
html page to the following CGI and then hit the "read cookie" link.  Of
course if you wait 30 sec (expires) the cookie will not be there, but hit
the link again and it magically reappears:

#!/usr/bin/perl -w
use CGI;
$ref = '<script>document.write(document.referrer)</script>';
$q = new CGI;
$cookie = $q->cookie(-name=>'drf', -value=>$ref, -expires=>'+30s');
print $q->header(-content=>'text/html', -cookie=>$cookie),$q->start_html,
$cookie->value([$ref]),$q->p,$q->a({href=>$q->url()},'read cookie'),$q->p;
if ($q->cookie('drf')) { print "Got cookie ".$q->cookie('drf'),"\n"; }
print $q->end_html;


Sample browser ouput after "read cookie" link:

http://localhost/~efflandt/jstest.html

read cookie

Got cookie http://localhost/~efflandt/jstest.html

-- 
David Efflandt  (Reply-To is valid)  http://www.de-srv.com/
http://www.autox.chicago.il.us/  http://www.berniesfloral.net/
http://cgi-help.virtualave.net/  http://hammer.prohosting.com/~cgi-wiz/


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

Date: Tue, 19 Jun 2001 09:02:05 +0300
From: "Vassilis G. Tavoultsidhs" <ixanthi@ixanthi.gr>
Subject: multiple file upload
Message-Id: <9gmq1b$o02$1@foo.grnet.gr>

Hi, I don't know if this is the correct newsgroup but anyway.
I want to make a script to upload multiple files from the users browser to
my server. I have tried the following :

     $write_file = "../mydir/images/myfile.jpg";
     $filepath = "file.jpg";
     $bytes_read=0;
     $size='';
     $buff='';

     open (WFD,">$write_file") || die "Error opening ${write_file} for
writing \n";
     flock (WFD, "1");

     while ($bytes_read=read($filepath,$buff,2096))
     {
         $size += $bytes_read;
         binmode WFD;
         print WFD $buff;
     }

     close(WFD);

it does work for one file but if I repeat it for a different $writefile and
$filepath it will create a file on the server which will have no content.
Does anyone know what to do?

Thanks

Vassilis G. Tavoultsidhs
Electronics Engineer - Software Engineer
www.ixanthi.gr




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

Date: Mon, 18 Jun 2001 23:13:27 -0400
From: "kevin" <emailkevin@charter.net>
Subject: parsing log file
Message-Id: <titgl8jpfkj5bf@corp.supernews.com>

Can someone tell me a simple way to read a log file and act on it?...I mean
a REAL log file...one that is constantly updated...I need to know how to
read each new line as it comes in and take some action.  Any reference I
find is for a static log file...not a dynamic,  new entry a minute, log
file....ANY help appreciated!!

thanks




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

Date: 18 Jun 2001 22:12:58 -0500
From: Tony Curtis <tony_curtis32@yahoo.com>
Subject: Re: parsing log file
Message-Id: <877ky9upqd.fsf@limey.hpcc.uh.edu>

>> On Mon, 18 Jun 2001 23:13:27 -0400,
>> "kevin" <emailkevin@charter.net> said:

> Can someone tell me a simple way to read a log file and
> act on it?...I mean a REAL log file...one that is
> constantly updated...I need to know how to read each new
> line as it comes in and take some action.  Any reference
> I find is for a static log file...not a dynamic, new
> entry a minute, log file....ANY help appreciated!!

swatch, big brother, pikt, there are many.

Try poking around at e.g.

    http://freshmeat.net/
    http://www.stokely.com/

hth
t
-- 
Just reach into these holes.  I use a carrot.


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

Date: Tue, 19 Jun 2001 04:54:59 GMT
From: cfedde@fedde.littleton.co.us (Chris Fedde)
Subject: Re: parsing log file
Message-Id: <DWAX6.152$T3.170731520@news.frii.net>

In article <titgl8jpfkj5bf@corp.supernews.com>,
kevin <emailkevin@charter.net> wrote:
>Can someone tell me a simple way to read a log file and act on it?...I mean
>a REAL log file...one that is constantly updated...I need to know how to
>read each new line as it comes in and take some action.  Any reference I
>find is for a static log file...not a dynamic,  new entry a minute, log
>file....ANY help appreciated!!
>
>thanks
>
>

Many versions of tail have an option that lets it follow a file over log
roll events. On FreeBSD

    tail -F /var/log/all.log | my_parsing_program

works for me.

Good Luck
-- 
    This space intentionally left blank


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

Date: Mon, 18 Jun 2001 23:02:49 -0400
From: Benjamin Goldberg <goldbb2@earthlink.net>
Subject: Re: Performance Advice: CGI servers files
Message-Id: <3B2EC0D9.F5CF2FE8@earthlink.net>

Ted Smith wrote:
> 
> I have a simple cgi that takes files (below the doctree) and serves it
> to authenticated users over HTTPS.  I can't use FTP.  When the files
> are big, 20-30MB usually, it takes a while to download obviously.  The
> perl process is pretty high. And when there are a lot of people
> downloading, the server crawls. Anything I can do that you suggest?
> 
> I do a simple:
> 
> 1) Set content-disposition/content-type
> 2) open (FILE,"file.zip");
>    binmode(STDOUT);
>    while (<FILE>) {
>      print $_;
>    }
> 3) cleanup

1) binmode(STDOUT);
2) Set content-type/content-disposition
	remember to use "\015\012", not "\n" or "\r\n".
3)
	open( FILE, "<", "file.zip" ) or die "file.zip: $!";
	binmode(FILE);
	my $blocksize = (stat(FILE))[11] or 4096;
	local $/ = \$blocksize;
	print while( <FILE> );
	4) cleanup.

Always, yes, always, check the return value of open.

If you are on a system where binmode makes a difference, you need to set
it on both STDOUT and on FILE.

See http://www.perldoc.com/perl5.6/pod/perlport.html#Newlines for why
to use \015\012 to end header lines.

Reading fixed size blocks, rather searching for newlines, is much
faster, especially if you can pick the blocksize to be the preferred
blocksize for the file.

Setting $/ to a reference to a scalar containing an integer can make
code easier to read than using read() or sysread().  Don't forget to
localize the assignment to $/ .

The value 4096 as a default was chosen more-or-less arbitrarily.  I
assume that the file's blocksize is a power of two.  You should
experiment with various different powers of 2 to see which results in
the file loading fastest.

-- 
The longer a man is wrong, the surer he is that he's right.


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

Date: 19 Jun 2001 04:09:29 GMT
From: dave@sydney.daveb.net (Dave Bailey)
Subject: Re: Performance Advice: CGI servers files
Message-Id: <slrn9it9u6.70r.dave@sydney.daveb.net>

On Mon, 18 Jun 2001 23:02:49 -0400, Benjamin Goldberg 
<goldbb2@earthlink.net> wrote:
>Ted Smith wrote:
>> 
>> I have a simple cgi that takes files (below the doctree) and serves it
>> to authenticated users over HTTPS.  I can't use FTP.  When the files
>> are big, 20-30MB usually, it takes a while to download obviously.  The
>> perl process is pretty high. And when there are a lot of people
>> downloading, the server crawls. Anything I can do that you suggest?
>> 
>> I do a simple:
>> 
>> 1) Set content-disposition/content-type
>> 2) open (FILE,"file.zip");
>>    binmode(STDOUT);
>>    while (<FILE>) {
>>      print $_;
>>    }
>> 3) cleanup
[...]
>Reading fixed size blocks, rather searching for newlines, is much
>faster, especially if you can pick the blocksize to be the preferred
>blocksize for the file.
[...]
>The value 4096 as a default was chosen more-or-less arbitrarily.  I
>assume that the file's blocksize is a power of two.  You should
>experiment with various different powers of 2 to see which results in
>the file loading fastest.

If there are a lot of these files and your httpd processes are 
relatively large, and you're experiencing heavy traffic, the 
kernel won't be able to cache a file in memory without swapping
httpds or flushing other, previously cached files.  The problem
is that the httpds all have to sit there like pigs while these
huge files are ambling their way down the connection to the 
client, and with big files, you're likely to have lots of 
concurrent connections since the average connection time is huge, 
hence lots of httpd processes swapping in and out while your disk 
gets nailed left and right.  If you have lots of time, the ideal 
solution is to write a single-threaded, one-process event driven 
server which sits on another port and handles the work of actually 
transferring the files.  Then you can redirect from Apache to this 
server when it's time to actually send a file, thus freeing up the 
httpd much sooner and reducing the average number of them which are
needed to handle a given client load.  

BTW, if using Apache/mod_perl to serve files, you can use the Apache
request object's send_fd method, which essentially does what Ben
is doing here, but with a blocksize of 8192 bytes.  For example:

use Apache;
use Apache::Constants qw(NOT_FOUND OK);

 ...
 
open(FH, $file) || return NOT_FOUND;
$r->content_type('application/x-whatever');
$r->header_out('Content-Length'=>(stat($file))[7]);
$r->send_http_header;
$r->send_fd(\*FH);
close(FH);
return OK;

--
Dave Bailey
davidb54@yahoo.com


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

Date: Tue, 19 Jun 2001 04:21:53 GMT
From: cfedde@fedde.littleton.co.us (Chris Fedde)
Subject: Re: Performance Advice: CGI servers files
Message-Id: <BrAX6.150$T3.191580672@news.frii.net>

In article <9d2caaf1.0106181258.2598b6e1@posting.google.com>,
Ted Smith <bluearchtop@my-deja.com> wrote:
>I have a simple cgi that takes files (below the doctree) and serves it
>to authenticated users over HTTPS.  I can't use FTP.  When the files
>are big, 20-30MB usually, it takes a while to download obviously.  The
>perl process is pretty high. And when there are a lot of people
>downloading, the server crawls. Anything I can do that you suggest?
>
>I do a simple:
>
>1) Set content-disposition/content-type
>2) open (FILE,"file.zip");
>   binmode(STDOUT);
>   while (<FILE>) {
>     print $_;
>   }
>3) cleanup

Pardon me but what is all this hoopla about data transfer for
anyway?  I thought that webservers were optimized for serving files.
Use a CGI to present a menu if you want to, but have the CGI cause
a redirect to the data file and let the webserver do what it is
good at. You may have to associate a Content-Type with the file
extension in the servers configuration to get the right behavior
in the browser when the transfer starts coming in.

Good Luck
-- 
    This space intentionally left blank


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

Date: Mon, 18 Jun 2001 17:31:44 +0800
From: "John Lin" <johnlin@chttl.com.tw>
Subject: tee revisited: dup STDOUT to a file but still get output from both
Message-Id: <9gmh7j$ifc@netnews.hinet.net>

Dear all,

I'm sorry if you feel the question is often asked, but this is different.
I found neither the FAQ, IO::Tee, IO::File::Multi could solve my problem.

My goal is like this:
(Note: I don't want to use external "tee" because I am running on WinNT.)

----------------------- hello.pl
print "hello";

======================= normal run, will show "hello" on console
perl hello.pl

======================= use X.pm to redirect (actually "tee") the output
perl -MX hello.pl

so I can see "hello" both on console and a file "x.txt".

My trials were all based on this X.pm

--------------------------- X.pm
open F,">x.txt" or die "can't create x.txt";
open STDOUT,">&F" or die "fail to dup";
1

This basic module is not my goal because nothing comes out from STDOUT.
So I need to make some modification.

My trials were
--------------------------- X.pm
use IO::Tee;
my $tee = new IO::Tee(">x.txt") or die "can't create x.txt";
open STDOUT,">&$tee" or die "fail to dup";
1

fail to dup at X.pm line 3.
Compilation failed in require.
BEGIN failed--compilation aborted.

or

open STDOUT,">&".fileno($tee) or die "fail to dup";

Can't locate object method "FILENO" via package "IO::Tee" at X.pm line 3.
Compilation failed in require.
BEGIN failed--compilation aborted.

or
--------------------------- X.pm
use IO::Tee;
my $tee = new IO::Tee(">x.txt") or die "can't create x.txt";
tie *STDOUT,'IO::Tee',$tee;
1

Compile OK, but nothing comes out from STDOUT.

or

my $tee = new IO::Tee(">x.txt",\*STDOUT) or die "can't create x.txt";
tie *STDOUT,'IO::Tee',$tee;

Danger!!! Infinite loop!!!

Could you help me with how to make it work using IO::Tee here?
Or do you know any other existing module that would help?

Note that all the magic must be done in the module X.pm only so that
the user don't need to change anything in his file.
(Thus,  print $tee "hello";  is not the answer.)

Thank you very much.

John Lin





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

Date: Tue, 19 Jun 2001 00:25:11 -0400
From: Benjamin Goldberg <goldbb2@earthlink.net>
Subject: Re: tee revisited: dup STDOUT to a file but still get output from both
Message-Id: <3B2ED427.7A659688@earthlink.net>

John Lin wrote:
> 
> Dear all,
> 
> I'm sorry if you feel the question is often asked, but this is
> different. I found neither the FAQ, IO::Tee, IO::File::Multi could
> solve my problem.
> 
> My goal is like this:
> (Note: I don't want to use external "tee" because I am running on
> WinNT.)
> 
> ----------------------- hello.pl
> print "hello";
> 
> ======================= normal run, will show "hello" on console
> perl hello.pl
> 
> ======================= use X.pm to redirect (actually "tee") the
> output perl -MX hello.pl
> 
> so I can see "hello" both on console and a file "x.txt".
[snip]
> Could you help me with how to make it work using IO::Tee here?
> Or do you know any other existing module that would help?
> 
> Note that all the magic must be done in the module X.pm only so that
> the user don't need to change anything in his file.
> (Thus,  print $tee "hello";  is not the answer.)

This is just a guess, but try putting this in X.pm:

use IO::tee;
my $tee = IO::tee->new( ">x.txt", \*STDOUT )
	or die qq{IO::tee->new( ">x.txt", \\*STDOUT ) : $!\n};
*STDOUT = $tee;
END {
	my ($x, $stdout) = $tee->handles;
	close $x;
	*STDOUT = $stdout;
}
1;


-- 
The longer a man is wrong, the surer he is that he's right.


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

Date: Tue, 19 Jun 2001 14:41:35 +0800
From: "John Lin" <johnlin@chttl.com.tw>
Subject: Re: tee revisited: dup STDOUT to a file but still get output from both
Message-Id: <9gms1s$9dt@netnews.hinet.net>

"Benjamin Goldberg" wrote
> John Lin wrote:
> > ----------------------- hello.pl
> > print "hello";
> > ================ use X.pm to redirect (actually "tee") the output
> > perl -MX hello.pl
> >
> > so I can see "hello" both on console and a file "x.txt".

> This is just a guess, but try putting this in X.pm:
> use IO::tee;
> my $tee = IO::tee->new( ">x.txt", \*STDOUT )
> or die qq{IO::tee->new( ">x.txt", \\*STDOUT ) : $!\n};
> *STDOUT = $tee;
> END {
> my ($x, $stdout) = $tee->handles;
> close $x;
> *STDOUT = $stdout;
> }
> 1;

Result:  x.txt was truncated but neither x.txt nor console has "hello".
(I rectified IO::tee into IO::Tee to make it work.)
Thank you.
John Lin





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

Date: 6 Apr 2001 21:33:47 GMT (Last modified)
From: Perl-Users-Request@ruby.oce.orst.edu (Perl-Users-Digest Admin) 
Subject: Digest Administrivia (Last modified: 6 Apr 01)
Message-Id: <null>


Administrivia:

The Perl-Users Digest is a retransmission of the USENET newsgroup
comp.lang.perl.misc.  For subscription or unsubscription requests, send
the single line:

	subscribe perl-users
or:
	unsubscribe perl-users

to almanac@ruby.oce.orst.edu.  

To submit articles to comp.lang.perl.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 1156
***************************************


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