[17928] in Perl-Users-Digest
Perl-Users Digest, Issue: 88 Volume: 10
daemon@ATHENA.MIT.EDU (Perl-Users Digest)
Thu Jan 18 09:05:41 2001
Date: Thu, 18 Jan 2001 06:05:10 -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: <979826710-v10-i88@ruby.oce.orst.edu>
Content-Type: text
Perl-Users Digest Thu, 18 Jan 2001 Volume: 10 Number: 88
Today's topics:
$FindBin::Bin for modules <johnlin@chttl.com.tw>
Re: $FindBin::Bin for modules (Rafael Garcia-Suarez)
Re: $FindBin::Bin for modules nobull@mail.com
Re: $foo{$bar}={x=>$x,y=>$y} v. $foo{$bar}{x}=$x etc? <visstmbl@reading.ac.uk>
Re: Call C function in XS from C function in the same X <active_ingy@my-deja.com>
change unlink() to delete() (was Re: rename function in (Tad McClellan)
Re: Child processes don't clean up (defunct processes l (Villy Kruse)
Re: Child processes don't clean up (defunct processes l <geoff-at-farmline-dot-com@127.0.0.1>
Re: FAQ 9.10: How do I redirect to another page? (Anno Siegel)
flock problem... <Waarddebon@chello.nl>
Re: How can I send my file to the printer in win98 by a <jck1@seed.net.tw>
Re: How can I send my file to the printer in win98 by a <gracenews@optusnet.com.au>
Re: How do you detect modem rings in Perl (if possible) <c.manley@chello.nl>
Re: How to Create a Perl Shared Library (.so file) ? <briani@activestate.com>
Is this the BEST way ? hafateltec@hotmail.com
Re: Is this the BEST way ? (Rafael Garcia-Suarez)
Re: LWP Syntax help.... (Tad McClellan)
Re: novice perl programmer w/ errors (Rafael Garcia-Suarez)
Re: novice perl programmer w/ errors (Tad McClellan)
passing parameters from command line? (Ted)
Re: passing parameters from command line? (Bernard El-Hagin)
Re: passing parameters from command line? <dfortin@eftia.com>
Re: passing parameters from command line? <remi@multiweb.nl>
Re: passing parameters from command line? (Bernard El-Hagin)
Perl - mySQL richard_dobson@my-deja.com
Re: Perl - mySQL (Damian James)
Re: Perl - mySQL <kstep@pepsdesign.com>
Re: Perl/IIS and open() <nospam-abuse@[127.0.0.1]>
Re: Perl/IIS and open() <tward10@jaguar.com>
Re: Pulling KEy out of hash (Tad McClellan)
Re: Random text script, got one?:-) <nospam-abuse@[127.0.0.1]>
Re: regular expression question. pls help (Tad McClellan)
Digest Administrivia (Last modified: 16 Sep 99) (Perl-Users-Digest Admin)
----------------------------------------------------------------------
Date: Thu, 18 Jan 2001 16:30:18 +0800
From: "John Lin" <johnlin@chttl.com.tw>
Subject: $FindBin::Bin for modules
Message-Id: <9469ma$7l5@netnews.hinet.net>
Dear all,
My module needs to know where itself is stored because it wants
to open a data file stored in the same directory. For example:
mail.pl ---------- stored in /maindir
use A;
A::hello;
A.pm ------------- stored in /john/lib, included in PERL5LIB
package A;
open F,'data.txt' or die $!;
my @data = <F>;
sub hello { print @data }
1
data.txt --------- stored with A.pm (in /john/lib)
------------------ invoke main.pl from /rundir
rundir> perl /maindir/main.pl
No such file or directory at /john/lib/A.pm line 2.
Compilation failed in require at /maindir/main.pl line 2.
BEGIN failed--compilation aborted at /maindir/main.pl line 2.
Oh, oh, A.pm can't find data.txt, even they are stored together.
I can't use $FindBin::Bin to solve this because it only knows
where main.pl is stored.
use FindBin;
open F,"$FindBin::Bin/data.txt" or die $!;
# the same error messages
print $FindBin::Bin; # put it before the "open"
/maindir
How can a module open a file that is stored together with itself?
Thank you.
John Lin
------------------------------
Date: Thu, 18 Jan 2001 10:28:07 GMT
From: rgarciasuarez@free.fr (Rafael Garcia-Suarez)
Subject: Re: $FindBin::Bin for modules
Message-Id: <slrn96dhad.kso.rgarciasuarez@rafael.kazibao.net>
John Lin wrote in comp.lang.perl.misc:
>
> My module needs to know where itself is stored because it wants
> to open a data file stored in the same directory.
Use the %INC hash, described in perlvar.
Test case:
Let quux.pm contain :
package quux;
print $INC{'quux.pm'};
1;
Put it somewhere where perl can find it.
Then :
perl -Mquux -le1
will print the location of quux.pm.
--
# Rafael Garcia-Suarez / http://rgarciasuarez.free.fr/
#!/usr/bin/perl -p
BEGIN { *ARGV=*DATA }
__END__
Just another Perl hacker,
------------------------------
Date: 18 Jan 2001 13:34:58 +0000
From: nobull@mail.com
Subject: Re: $FindBin::Bin for modules
Message-Id: <u9k87tf0fx.fsf@wcl-l.bham.ac.uk>
"John Lin" <johnlin@chttl.com.tw> writes:
> My module needs to know where itself is stored because it wants
> to open a data file stored in the same directory.
A module can access its own filename using __FILE__.
--
\\ ( )
. _\\__[oo
.__/ \\ /\@
. l___\\
# ll l\\
###LL LL\\
------------------------------
Date: Thu, 18 Jan 2001 09:46:11 +0000
From: John Stumbles <visstmbl@reading.ac.uk>
To: Abigail <abigail@foad.org>, <gnari@my-deja.com>, Bart Lateur <bart.lateur@skynet.be>
Subject: Re: $foo{$bar}={x=>$x,y=>$y} v. $foo{$bar}{x}=$x etc?
Message-Id: <Pine.WNT.4.30.0101180935320.168-100000@supc16.rdg.ac.uk>
On 17 Jan 2001, Abigail wrote:
> John Stumbles (visstmbl@reading.ac.uk) wrote on MMDCXCVI September
> MCMXCIII in <URL:news:Pine.WNT.4.30.0101171332230.163-100000@supc16.rdg.ac.uk>:
> :}
> :} Yes I do have a loop: I'm querying a mySQL database using the DBI:
> :}
> :} while ($sth->fetch)
...
> If you manage to save more $MACs in some variant, you are hiding essential
> code.
On Wed, 17 Jan 2001, Bart Lateur wrote:
> I agree with Abigail ("Insufficient data"), but I'd venture a guess
> anyway. It's not uncommon that your hash keys don't differ from each
> other. Print out the keys every time you do an assignment, and maybe
> you'll find the error that way.
Sorry if I didn't make it clear: I'm getting the values of
$ifIndex, $Name, $Speed, $MAC etc from the database with each $sth->fetch.
And I did print out my $MAC hash keys (in fact everything I got
from the fetch()) and satisfied myself that I was getting the values I
expected.
However gnari sussed the problem:
On Wed, 17 Jan 2001 gnari@my-deja.com wrote:
> > # $ifTable{$ifIndex} = {
> > # Name => $Name,
> > # Speed => $Speed,
> > # } ;
> > $ifTable{$ifIndex}{Name} = $Name ;
> > $ifTable{$ifIndex}{Speed} = $Speed ;
>
> the difference between these two is that the first one creates
> a new hash with only 2 members ,but the second one adds/changes 2
> members of a hash that may already exist and leaves any other members
> unchanged, for example $ifTable{$ifIndex}{dot1d}
>
> so if you are also setting $ifTable{$ifIndex}{dot1d}{$MAC} with
> different values for $MAC within the loop, and expect to collect
> them all, you should not use the first method.
>
> hope this makes it clear
So I'm creating a new anonymous hash(ref):
{ Name => $Name, Speed => $Speed }
and assigning it to $ifTable{$ifIndex}, overwriting the {dot1d} member
with its {$MAC} keys each time?
- D'oh!
thanks, gnari!
regards,
--
John Stumbles j.d.stumbles@reading.ac.uk
I.T. Services Centre, University of Reading http://www.rdg.ac.uk/~visstmbl
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
never generalise
------------------------------
Date: Thu, 18 Jan 2001 11:46:36 GMT
From: Brian Ingerson <active_ingy@my-deja.com>
To: john@imining.com.tw
Subject: Re: Call C function in XS from C function in the same XS file
Message-Id: <946l2r$t5n$1@nnrp1.deja.com>
In article <93tos9$ium@netnews.hinet.net>,
"John" <john@imining.com.tw> wrote:
> Hi:
>
> I have a function ShowCounter() in WebGet.xs
> When I call ShowCounter() from another function in WebGet.xs, I get the
> following error.
>
> perl: error in loading shared libraries: blib/arch/auto/WebGet/WebGet.so:
> undefined symbol: ShowCounter
>
> But I can call ShowCounter() from my perl program that use module WebGet.
> I really have to call ShowCounter() in other C functions in WebGet.xs.
> How should I do?
The Inline module, which allows you to write C extensions without having
to bother with XS (or compiling for that matter) comes with a Cookbook
of examples. One of the examples answers the question you have asked.
Here's another complete program from a paper I wrote recently. It shows
how to call the same function from Perl and C, and also how to keep a
function from binding to Perl by declaring it static.
--------------------------------------------------
print "9 + 5 = ", add(9, 5), "\n";
print "SQRT(9^2 + 5^2) = ", pyth(9, 5), "\n";
print "9 * 5 = ", mult(9, 5), "\n";
use Inline C => <<'END_C';
int add(int x, int y) {
return x + y;
}
static int mult(int x, int y) {
return x * y;
}
double pyth(int x, int y) {
return sqrt(add(mult(x, x), mult(y, y)));
}
END_C
This produces:
9 + 5 = 14
SQRT(9^2 + 5^2) = 10.295630140987
Can't locate auto/main/mult.al in @INC ...
----------------------------------------------------
HTH, Brian
--
perl -le 'use Inline C=>q{SV*JAxH(char*x){return newSVpvf
("Just Another %s Hacker",x);}};print JAxH+Perl'
Sent via Deja.com
http://www.deja.com/
------------------------------
Date: Thu, 18 Jan 2001 14:01:16 GMT
From: tadmc@augustmail.com (Tad McClellan)
Subject: change unlink() to delete() (was Re: rename function in CGI script?)
Message-Id: <slrn96dmnh.4k2.tadmc@tadmc26.august.net>
Rand Simberg <simberg.interglobal@trash.org> wrote:
>On Thu, 18 Jan 2001 05:45:08 GMT, in a place far, far away,
>garry@zvolve.com (Garry Williams) made the phosphor on my monitor glow
>in such a way as to indicate that:
Your cutsie attribution string is too long.
>>>Also, how in the heck does one delete a file?
>>
>> perldoc -f unlink
>
>Ahhh, when I looked up unlink in the book, it actually had the syntax
^^^^^^^^
>for it.
>
>Is it supposed to be obvious that that's a file delete command?
Gee, I sure hope not, because it is not a file delete command.
[but it would be obvious to a C programmer 'cause unlink()
is the name of the C library function that ends up getting
called.
man unlink (my underlining):
NAME
unlink - delete a name and possibly the file it refers to
^^^^^^
]
You can successfully call unlink() and have the file *still be there*,
not the semantics usually associated with the word "delete" :-)
Many folks seem to think that unlink() should be named delete()
(or something else, as that is already taken) because people
don't look for "unlink" when trying to find out how to delete
a file.
So many in fact, that changing unlink()'s name was considered
for Perl 6:
http://dev.perl.org/rfc/29.pod
After some discussion, it was decided to not change
it for the reasons given there.
>Is
>there some reason they couldn't have a mention of delete when it came
>to "file" in the index of the book? ;-)
^^^^^^^^
There are hundreds of Perl books. Care to narrow it down to
a particular book?
Books are of but passing interest anyway.
The standard Perl docs, OTOH, are of extreme interest. Was there
someplace in the standard docs that could have helped you find
it faster?
I think the docs can be improved by either:
a FAQ: "How do I delete a file"
(including a brief description of what a "link" is)
or adding to
perldoc -f delete
"If you are looking for a function to delete I<files> then
see L</unlink>."
I think the question comes up enough that the docs should be
updated. I'll submit a patch for the second one when I get
some tuits.
--
Tad McClellan SGML consulting
tadmc@augustmail.com Perl programming
Fort Worth, Texas
------------------------------
Date: 18 Jan 2001 09:19:02 GMT
From: vek@pharmnl.ohout.pharmapartners.nl (Villy Kruse)
Subject: Re: Child processes don't clean up (defunct processes left) even though SIGCHLD does wait()
Message-Id: <slrn96dd85.ej0.vek@pharmnl.ohout.pharmapartners.nl>
On Wed, 17 Jan 2001 16:31:11 -0000,
Geoff Winkless <geoff-at-farmline-dot-com@127.0.0.1> wrote:
>
>Note that I set $SIG{CHLD} to \&deadbabe, which simply sets a variable to
>the result of wait() and resets $SIG{CHLD} again. All of this was taken
>pretty much verbatim from the perldocs.
>
>The question is, why would a child die but not pass a sigchld to its parent?
>Is it to do with the fact that later (in the child) we use `` to call things
>like the virus scanner?
>
It can happen that two children terminates at the same time, but as
sitnals are not queued the parent only sees one SIGCHLD. Then you will
see that the first child leaves no zombie but the second does.
If you send the parent process a SIGCHLD using the kill command and
the one of the zombies goes away, then this is the explanation.
To fix it, use waitpid(-1,&WNOHANG) in a loop until no pid is returned.
Note, that some ancient unix systems doesn't support waitpid, but those
are real ancient anyway.
From perldoc -f wiatpid:
=item waitpid PID,FLAGS
Waits for a particular child process to terminate and returns the pid
of the deceased process, or -1 if there is no such child process. The
status is returned in C<$?>. If you say
use POSIX ":sys_wait_h";
...
waitpid(-1,&WNOHANG);
then you can do a non-blocking wait for any process. Non-blocking wait
is available on machines supporting either the waitpid(2) or
wait4(2) system calls. However, waiting for a particular pid with
FLAGS of 0 is implemented everywhere. (Perl emulates the system call
by remembering the status values of processes that have exited but have
not been harvested by the Perl script yet.)
--
Villy
------------------------------
Date: Thu, 18 Jan 2001 09:32:44 -0000
From: "Geoff Winkless" <geoff-at-farmline-dot-com@127.0.0.1>
Subject: Re: Child processes don't clean up (defunct processes left) even though SIGCHLD does wait()
Message-Id: <946d50$ed3$1@soap.pipex.net>
"Villy Kruse" <vek@pharmnl.ohout.pharmapartners.nl> wrote in message
news:slrn96dd85.ej0.vek@pharmnl.ohout.pharmapartners.nl...
: On Wed, 17 Jan 2001 16:31:11 -0000,
: Geoff Winkless <geoff-at-farmline-dot-com@127.0.0.1> wrote:
: >Note that I set $SIG{CHLD} to \&deadbabe, which simply sets a variable to
: >the result of wait() and resets $SIG{CHLD} again. All of this was taken
: >pretty much verbatim from the perldocs.
: >
: >The question is, why would a child die but not pass a sigchld to its
parent?
: >Is it to do with the fact that later (in the child) we use `` to call
things
: >like the virus scanner?
: It can happen that two children terminates at the same time, but as
: sitnals are not queued the parent only sees one SIGCHLD. Then you will
: see that the first child leaves no zombie but the second does.
[snip rest of very lucid explanation]
Thanks Villy, this was very clear. I didn't use waitpid() because I wanted
the code to be as portable as possible, I guess we'll just have to put in an
install-time configuration option.
Geoff
------------------------------
Date: 18 Jan 2001 10:44:14 GMT
From: anno4000@lublin.zrz.tu-berlin.de (Anno Siegel)
Subject: Re: FAQ 9.10: How do I redirect to another page?
Message-Id: <946hdu$f95$1@mamenchi.zrz.TU-Berlin.DE>
Alan J. Flavell <flavell@mail.cern.ch> wrote in comp.lang.perl.misc:
[...]
>There's other things that seem to be wrong with this FAQ, but after
>I'd tried to raise them a few times, and in fact put some effort into
>writing some new text based on some very helpful discussions here with
>the regulars, it seemed to fly like a lead balloon when I tried to
>raise it with the Perlbugs folks, so I got dispirited.
Don't be. In my experience doc patches are silently incorporated
in one release or another (not necessarily the earliest possible).
Of course this assumes a reasonable patch, but from the quality of
your posts here and elsewhere I have no doubt about that.
Anno
------------------------------
Date: Thu, 18 Jan 2001 09:50:19 GMT
From: "Waarddebon" <Waarddebon@chello.nl>
Subject: flock problem...
Message-Id: <v%y96.747022$%C1.9404972@Flipper>
The lines below show an add and list DBM code. Problem with these lines is
that the files cant be flocked.
Can you rewrite these lines (from both add and list) so that the files are
flocked while writing and/or
reading to them ?
Add.pl
------------------------------------
#!/usr/local/bin/perl
## Flush the output buffer after each print
$|++;
## Print the MIME header
print "Content-type: text/html\n\n";
use CGI;
$query=new CGI;
## Read the HTML variables from the HTML form to PERL.
$name=$query->param('name');
$job=$query->param('job');
$stat=$query->param('stat');
## Build the string variable
$string = "name=" . $name . "&job=" . $job . "&stat=" . $stat;
## We have used the complete path to the file
dbmopen(%DB, "/data1/hm/oostwijk/database/namejobstat", 0664) || die $!;
## Create an entry in the hash using the username as the key
$DB{$name} = $string;
dbmclose(%DB);
print "<B>$name</B>, your entry has been added to our database!.\n";
List.pl
-----------------------------------------
#!/usr/local/bin/perl
use Time::Local;
print "Content-type: text/html", "\n\n";
print "", "\n";
&listDB();
sub listDB {
dbmopen(%DB, "/data1/hm/dewaard/database/sell", 0664) || die $!;
foreach $key (keys %DB){
$string = $DB{$key};
($name, $job, $status) = split ( "&", $string );
($foo,$name) = split ("=", $name);
($foo,$job) = split ("=", $job);
($foo,$status) = split ("=", $status);
print "$name is a $job and his/her", " status is $status\n";
#print "$DB{$key}";
}
dbmclose(%DB); }
These lines I've seen somewhere on the internet..but can I use them (and
how, please rewrite) in the
above lines ?
&dbconnect;
$db->do("LOCK TABLES TableItemsOpen WRITE");
#
#
#Do your db stuff here
#
#
$db->do("UNLOCK TABLES");
&dbdisconnect;
Note: I can't make use of any Module (but one: the Cgi module) since I am on
the Hypermart server.
------------------------------
Date: Thu, 18 Jan 2001 16:44:42 +0800
From: "jck1" <jck1@seed.net.tw>
Subject: Re: How can I send my file to the printer in win98 by activeperl
Message-Id: <946ar8$a5d@netnews.hinet.net>
Hello,
I write a small script which can produce a file.
In the past, I open the file to print by the "MS Word" after the perl
script finished.
But it is inconvenient. How can I print the file using the perl command.
I know the perl command "print" which I can refer the filehandle.
But in the win98, not like the unix, the printer is not seen as a device.
How can I do? And give me a example.
Thanks in advance,
Jck1
------------------------------
Date: Thu, 18 Jan 2001 22:30:59 +1000
From: "Jeffrey Grace" <gracenews@optusnet.com.au>
Subject: Re: How can I send my file to the printer in win98 by activeperl
Message-Id: <3a66e236$0$15464$7f31c96c@news01.syd.optusnet.com.au>
"jck1" <jck1@seed.net.tw> wrote in message
news:946ar8$a5d@netnews.hinet.net...
>
> How can I do? And give me a example.
>
> Thanks in advance,
> Jck1
>
In DOS you can redirect output to serial or parrel ports by sending to COMx
or LPTx or PRN (usually just a pointer to LPT1). eg: type autoexec.bat >
LPT1, will print the details on the printer (assuming the printer is set up
to print in a MS-DOS prompt, its an option when adding the printer driver).
I tried the following and it seems to do what you want, please note that the
page will stay in the printer (and a laser printer won't even start) until
you send a form feed, I don't know which character to send for this though.
Also even inkjets may buffer some of your output before you do a form feed.
---------
#!/perl/bin/perl -w
use Strict;
open (DATA, ">>LPT1") or die("Error opening printer port: $_");
print DATA "test\n";
close (DATA);
---------
On a related note, if I use the -T option on the shebang line (eg: #!
/perl/bin/perl -Tw) I get the following error: Too late for "-T" option at
test.pl line 1.
I use this exact line in my CGI scripts without problems, does anyone know
what I'm doing wrong here?
cheers,
Jeffrey Grace
~~~~~~~~~~~~~~~~~~~~
Queensland, Australia
------------------------------
Date: Thu, 18 Jan 2001 13:37:40 +0100
From: Craig Manley <c.manley@chello.nl>
Subject: Re: How do you detect modem rings in Perl (if possible)?
Message-Id: <3A66E394.C8C1BC32@chello.nl>
For those interested, I finally got hold of a PC with a modem and tested
my idea. It worked using Linux, but not with Windows. That was the same
PC and the modem is on COM3 in Windows. When using Windows the script
opens the modem device successfully but never reads any data from the
modem. The code I used is below. Has anybody got any idea why this
happens?
-Craig Manley
#!/usr/bin/perl -w
#
use strict;
my $lv_Mdm;
if ($^O eq 'MSWin32') {
$lv_Mdm = 'COM3'; # My modem is on COM3
}
else {
$lv_Mdm = '/dev/modem';
}
# Reset modem
print "Resetting modem...\n";
unless(open(F,">$lv_Mdm")) {
die "Failed to open modem device.\n";
}
print F "AT&E0\n";
close(F);
# Listen for rings
print "Listening on modem device for rings...\n";
unless(open(F,$lv_Mdm)) {
die "Failed to open modem device.\n";
}
while (<F>) {
chomp($_);
unless($_) {
next;
}
print ">$_\n";
if ($_ eq 'RING') {
print 'Pinging internet...';
if ($^O eq 'MSWin32') {
system('ping -n 1 195.64.68.254 >nul');
}
else {
system('ping -c 1 195.64.68.254 >/dev/null 2>&1');
}
print "OK\n";
}
}
close(F);
------------------------------
Date: Thu, 18 Jan 2001 11:14:51 GMT
From: Brian Ingerson <briani@activestate.com>
Subject: Re: How to Create a Perl Shared Library (.so file) ?
Message-Id: <946j76$rs0$1@nnrp1.deja.com>
In article <944qui$cop$1@nnrp1.deja.com>,
hmug@my-deja.com wrote:
> Hi Anno,
>
> Many Thanks!! I was nearly running mad!
>
> Might you know how I can embed perl in C? Or do you have any nice
> pointers?
If you are familiar with Inline.pm as a way to extend Perl with C,
Inline::CPR is a very simple way to embed Perl in C. You just put a
hashbang line:
#!/usr/bin/cpr
at the top of your C source file, and then run the source. Really! As an
added bonus you'll have automatic access to the PerlAPI. You don't have
to start a perl interpreter, because your entire C program is already
running _under_ a perl interpreter.
The module's not as robust as Inline yet, but it's quite easy and a bit
of fun too.
Brian
--
perl -le 'use Inline C=>q{SV*JAxH(char*x){return newSVpvf
("Just Another %s Hacker",x);}};print JAxH+Perl'
Sent via Deja.com
http://www.deja.com/
------------------------------
Date: Thu, 18 Jan 2001 08:05:43 GMT
From: hafateltec@hotmail.com
Subject: Is this the BEST way ?
Message-Id: <94684l$is4$1@nnrp1.deja.com>
#!/usr/bin/perl -w
use strict;
use DBI();
#opens a database connection
my $dbh = DBI->connect
("dbi:mysql:database=phone;host=localhost","root", "hafa") or die
"Couldn't connect to database address: " .
DBI::errstr;
$dbh->{PrintError} = 0; # Do Not Print errors.
$dbh->{RaiseError} = 1; # Die on errors, and display to
browser.
while (<>) {
chomp;
#regex checks for valid input xxx-xxxx phone number
if ($_ =~ /^\d{3}-\d{4}$/) {
my $sth = $dbh->prepare("SELECT * FROM phone where number = '$_'");
$sth->execute();
while (my @row = $sth->fetchrow_array) {
print "@row\n";
my $number = shift @row;
my $first = shift @row;
my $last = shift @row;
print "$number\n";
print "$first\n";
print "$last\n";
}
}
}
$dbh->disconnect;
Is this the BEST way to do this?
1. Open connection to MySQL Database
2. Get input from user on requested search
3. Query database from the input
4. Print the results and/or shift the array result into individual
scalars for later use in the program.
I am looking for critique and suggestions as my quest to learn PERL
continues.
Thank You,
Michael
Sent via Deja.com
http://www.deja.com/
------------------------------
Date: Thu, 18 Jan 2001 08:34:43 GMT
From: rgarciasuarez@free.fr (Rafael Garcia-Suarez)
Subject: Re: Is this the BEST way ?
Message-Id: <slrn96dalo.ked.rgarciasuarez@rafael.kazibao.net>
hafateltec@hotmail.com wrote in comp.lang.perl.misc:
> #!/usr/bin/perl -w
> use strict;
Good.
> use DBI();
>
> #opens a database connection
> my $dbh = DBI->connect
> ("dbi:mysql:database=phone;host=localhost","root", "hafa") or die
> "Couldn't connect to database address: " .
> DBI::errstr;
> $dbh->{PrintError} = 0; # Do Not Print errors.
> $dbh->{RaiseError} = 1; # Die on errors, and display to
> browser.
>
> while (<>) {
> chomp;
> #regex checks for valid input xxx-xxxx phone number
> if ($_ =~ /^\d{3}-\d{4}$/) {
> my $sth = $dbh->prepare("SELECT * FROM phone where number = '$_'");
> $sth->execute();
Better way : prepare the $sth statement once, execute it many times.
This will probably improve performance. (depends on your DBD driver,
though). Suggested code :
my $sth = $dbh->prepare("SELECT * FROM phone where number = ?");
while (<>) {
chomp;
if ($_ =~ /^\d{3}-\d{4}$/) {
$sth->execute($_) or die $DBI::errstr; # or some other kind
# of error handling
# etc...
> while (my @row = $sth->fetchrow_array) {
> print "@row\n";
> my $number = shift @row;
> my $first = shift @row;
> my $last = shift @row;
> print "$number\n";
> print "$first\n";
> print "$last\n";
You can also write:
my ($number, $first, $last) = @row;
This is shorter and does not destroy the @row array.
> }
> }
> }
> $dbh->disconnect;
I would use an END block here :
END { $dbh->disconnect if $dbh }
ensuring proper deconnection even if the script died in the middle of
something.
--
# Rafael Garcia-Suarez / http://rgarciasuarez.free.fr/
- What kind of OSes do you usually have here ?
- Oh, we got both kinds. We got System V *and* BSD.
------------------------------
Date: Thu, 18 Jan 2001 14:01:13 GMT
From: tadmc@augustmail.com (Tad McClellan)
Subject: Re: LWP Syntax help....
Message-Id: <slrn96dg6s.4k2.tadmc@tadmc26.august.net>
cam <cam@home.com> wrote:
>
>I'm looking for a simple dictionary of perl syntax for parsing URL's using
^^^^^^^^^^^ ^
What is it that is possessed by a URL?
>LWP:Simple;
>
>I know how to get a URL, but can't find a guide to the syntax used to
>grab/edit it's content.
What you have described is NOT parsing URLs.
You want to parse HTML, not URLs.
Use one of the HTML::* modules from CPAN for that.
--
Tad McClellan SGML consulting
tadmc@augustmail.com Perl programming
Fort Worth, Texas
------------------------------
Date: Thu, 18 Jan 2001 08:07:38 GMT
From: rgarciasuarez@free.fr (Rafael Garcia-Suarez)
Subject: Re: novice perl programmer w/ errors
Message-Id: <slrn96d930.hut.rgarciasuarez@rafael.kazibao.net>
kenneth hopkins wrote in comp.lang.perl.misc:
> Hi again all -
> I have a simple program below that I have created to read in a file that
> contains only 6 digit integer number per line. Approx 500 lines. Then the
> number will be ran thru an informix database and then the results output to
> a new file. And I am recieving "201: A syntax error has occurred." I have
> lost too many of my braincell trying to figure it out and am turning to more
> compenent folks such as ya'll. Can you see my error? It would be very
> helpful if you could point it out to me and any other flaws you might see.
>
> Thanks oodles,
> kenny
>
> #!/usr/bin/perl -w
> use strict;
> use POSIX;
>
> my $num; # client_num retrieved from text file
> my $line;
>
> open (OUT, "|isql utell >/dev/null") or die;
> while(<>)
> {
> chomp;
> $num = $_;
For the sake of security, I would include here something like :
next if $num =~ /\D/;
> print OUT "
> UNLOAD TO \"/home/support/khopkins/isql.out\"
> SELECT client_type, client_id, client_num, name, title,
> first_name, middle_name, last_name, address1, address2,
> city, state, zip, country, home_phone, business_phone
> FROM client_ids
> WHERE client_num = '$num' ";
^^^
Shouldn't you use some kind of SQL statement separator here ? (e.g. a ';')
> }
> close(OUT);
Check the return value of close when you're writing to pipes.
close(OUT) or die "Close failed: $!\n";
--
# Rafael Garcia-Suarez / http://rgarciasuarez.free.fr/
use overload '""' => sub { print "Just another Perl hacker,\n" };
$_ = bless {}; print;
------------------------------
Date: Thu, 18 Jan 2001 14:01:13 GMT
From: tadmc@augustmail.com (Tad McClellan)
Subject: Re: novice perl programmer w/ errors
Message-Id: <slrn96dgrj.4k2.tadmc@tadmc26.august.net>
kenneth hopkins <khopkins3@home.com> wrote:
>And I am recieving "201: A syntax error has occurred."
All of the messages that perl might issue are documented in
the perldiag.pod standard doc.
perldoc perldiag
The message above is not there, so it is not a Perl message.
There is no syntax error in the Perl code below. You do
not have a Perl problem, so you are asking in the wrong place.
>#!/usr/bin/perl -w
>use strict;
Clever of you to use those. It keeps your posted code from being ignored :-)
> UNLOAD TO \"/home/support/khopkins/isql.out\"
> SELECT client_type, client_id, client_num, name, title,
> first_name, middle_name, last_name, address1, address2,
> city, state, zip, country, home_phone, business_phone
> FROM client_ids
> WHERE client_num = '$num' ";
Perhaps you have an SQL syntax error, in which case you should
ask in a newsgroup where SQL is discussed.
--
Tad McClellan SGML consulting
tadmc@augustmail.com Perl programming
Fort Worth, Texas
------------------------------
Date: Thu, 18 Jan 2001 12:22:09 GMT
From: tedius@gmx.co.uk (Ted)
Subject: passing parameters from command line?
Message-Id: <3a68dfef.531874671@news.datacomm.ch>
Hi!
just a short question: how can I pass some string to my perl script from
command line?
I need something like this:
script.pl STRING
#!/usr/bin/perl
$Foo=STRING
.........
Thanks,
Ted
--
you need to remove * * to reply by e-mail
--
------------------------------
Date: Thu, 18 Jan 2001 12:34:22 +0000 (UTC)
From: bernard.el-hagin@lido-tech.net (Bernard El-Hagin)
Subject: Re: passing parameters from command line?
Message-Id: <slrn96domd.2q0.bernard.el-hagin@gdndev25.lido-tech>
On Thu, 18 Jan 2001 12:22:09 GMT, Ted <tedius@gmx.co.uk> wrote:
>Hi!
>
>just a short question: how can I pass some string to my perl script from
>command line?
All of the command line arguments you pass to your Perl script are
stored in the @ARGV array, so use something like this:
my $first_arg = $ARGV[0];
my $second_arg = $ARGV[1];
and so on.
Cheers,
Bernard
--
#requires 5.6.0
perl -le'* = =[[`JAPH`]=>[q[Just another Perl hacker,]]];print @ { @ = [$ ?] }'
------------------------------
Date: Thu, 18 Jan 2001 08:19:39 -0500
From: "Dennis Fortin" <dfortin@eftia.com>
Subject: Re: passing parameters from command line?
Message-Id: <f4C96.121178$Z2.1457163@nnrp1.uunet.ca>
"Ted" <tedius@gmx.co.uk> wrote in message
news:3a68dfef.531874671@news.datacomm.ch...
> Hi!
>
> just a short question: how can I pass some string to my perl script from
> command line?
>
> I need something like this:
>
> script.pl STRING
>
>
>
> #!/usr/bin/perl
>
> $Foo=STRING
> .........
>
>
> Thanks,
>
> Ted
> --
>
> you need to remove * * to reply by e-mail
>
> --
You can also use the shift function;
ie:
================================
#! /usr/local/bin/perl - w
use strict; # Not necessary for this example, but I use it anyways ;)
$Foo = shift; # Will get ARGV[0]
$Bar = shift; # Will get ARGV[1]
# Insert rest of code here.
================================
As long as you call it at the beginning of the program, outside of a
function, and don't change the $_ variable, it should work.
D Fortin
------------------------------
Date: Thu, 18 Jan 2001 14:51:27 -0000
From: "paul" <remi@multiweb.nl>
Subject: Re: passing parameters from command line?
Message-Id: <DyC96.198$OG.86251@news.soneraplaza.nl>
------------CUT-----------
> You can also use the shift function;
>
> ie:
> ================================
>
> #! /usr/local/bin/perl - w
>
> use strict; # Not necessary for this example, but I use it anyways
;)
>
> $Foo = shift; # Will get ARGV[0]
> $Bar = shift; # Will get ARGV[1]
>
this raises the following question for me ..
can you assign for example -h <HOSTNAME> -p <PORT>
to ARGV array
or is the -h ARGV[0] <HOSTNAME> ARGV[1] etc etc ??
> # Insert rest of code here.
>
> ================================
> As long as you call it at the beginning of the program, outside of a
> function, and don't change the $_ variable, it should work.
>
> D Fortin
grx paul
------------------------------
Date: Thu, 18 Jan 2001 13:55:53 +0000 (UTC)
From: bernard.el-hagin@lido-tech.net (Bernard El-Hagin)
Subject: Re: passing parameters from command line?
Message-Id: <slrn96dtf8.2q0.bernard.el-hagin@gdndev25.lido-tech>
On Thu, 18 Jan 2001 14:51:27 -0000, paul <remi@multiweb.nl> wrote:
>------------CUT-----------
>
>> You can also use the shift function;
>>
>> ie:
>> ================================
>>
>> #! /usr/local/bin/perl - w
>>
>> use strict; # Not necessary for this example, but I use it anyways
>;)
>>
>> $Foo = shift; # Will get ARGV[0]
>> $Bar = shift; # Will get ARGV[1]
>>
>this raises the following question for me ..
>can you assign for example -h <HOSTNAME> -p <PORT>
>to ARGV array
>or is the -h ARGV[0] <HOSTNAME> ARGV[1] etc etc ??
Why don't you just check?
--------------------
#!/usr/bin/perl -w
$\ = "\n";
print shift @ARGV while @ARGV;
--------------------
Cheers,
Bernard
--
#requires 5.6.0
perl -le'* = =[[`JAPH`]=>[q[Just another Perl hacker,]]];print @ { @ = [$ ?] }'
------------------------------
Date: Thu, 18 Jan 2001 09:53:59 GMT
From: richard_dobson@my-deja.com
Subject: Perl - mySQL
Message-Id: <946efl$oe1$1@nnrp1.deja.com>
Hi, in the following line I am having problems:
$success = $dbh->do("UPDATE consumables set item='$item' where
book_no='$book_no'");
If $item is something like: 3.3' blah
problems occur in that the above will equate to:
$success = $dbh->do("UPDATE consumables set item='3.3' blah' where
book_no='$book_no'");
Does anyone know how I can somehow get the command to ignore the ' that
is present within $item ?
Thanks in advance
Rich
Sent via Deja.com
http://www.deja.com/
------------------------------
Date: 18 Jan 2001 10:35:08 GMT
From: damian@puma.qimr.edu.au (Damian James)
Subject: Re: Perl - mySQL
Message-Id: <slrn96dhob.sof.damian@puma.qimr.edu.au>
richard_dobson@my-deja.com posted the following to comp.lang.perl.misc
on Thu, 18 Jan 2001 09:53:59 GMT:
>
>Does anyone know how I can somehow get the command to ignore the ' that
>is present within $item ?
>
Yes, you need to check the documentation for DBI:
perldoc DBI
and look up the $dbh->quote() method. You would also be doing yourself a
favour if you go to 'perldoc perlop' and investigate Perl's quote-like
operators (q//, qq//, etc).
The other thing you might notice in the docs for DBI, is that if you use
placeholders, DBI will look after the quoting/escaping issues
automatically.
HTH
Cheers,
Damian
------------------------------
Date: Thu, 18 Jan 2001 09:01:44 -0500
From: "Kurt Stephens" <kstep@pepsdesign.com>
Subject: Re: Perl - mySQL
Message-Id: <946suf$8nt$1@slb3.atl.mindspring.net>
<richard_dobson@my-deja.com> wrote in message
news:946efl$oe1$1@nnrp1.deja.com...
> Hi, in the following line I am having problems:
>
> $success = $dbh->do("UPDATE consumables set item='$item' where
> book_no='$book_no'");
>
> If $item is something like: 3.3' blah
> problems occur in that the above will equate to:
>
> $success = $dbh->do("UPDATE consumables set item='3.3' blah' where
> book_no='$book_no'");
>
> Does anyone know how I can somehow get the command to ignore the ' that
> is present within $item ?
>
> Thanks in advance
> Rich
Two possible options - use the quote() function or bind the values using
placeholders. Sheck the DBI docs for details.
# Using quote()
$dbh->{RaiseError} = 1;
my $sql = sprintf "UPDATE consumables SET item=%s WHERE book_no=%s",
$dbh->quote($item), $dbh->quote($book_no);
$dbh->do($sql);
# Using implicit bind parameters
$dbh->{RaiseError} = 1;
my $sth = $dbh->prepare("UPDATE consumables SET item=? WHERE book_no=?");
$sth->execute($item, $book_no);
# Using explicit bind parameters
$dbh->{RaiseError} = 1;
my $sth = $dbh->prepare("UPDATE consumables SET item=? WHERE book_no=?");
$sth->bind_param(1, $item, DBI::SQL_VARCHAR);
$sth->bind_param(2, $book_no, DBI::SQL_VARCHAR);
$sth->execute;
HTH
Kurt Stephens
------------------------------
Date: Thu, 18 Jan 2001 03:54:37 -0500
From: "James Kauzlarich" <nospam-abuse@[127.0.0.1]>
Subject: Re: Perl/IIS and open()
Message-Id: <Mfy96.4569$d25.27602@newsfeed.slurp.net>
John Woltman <jew208@psu.edu> wrote in message
news:tPo96.125$cN.6302@bgtnsc07-news.ops.worldnet.att.net...
> if I use the same script to generate a link to
> the log file then the link works.
> like this:
> $filename = "/logs/log.txt";
> print "<a href=\"$filename\">link</a>"; # takes me to correct file
> open (HFILE, $filename); #bombs.
Remember that you are dealing with two different directory structures. The
root directory of your webpage is not the root directory of your web server.
But methinks this belongs in another newsgroup...
jmk
--
do NOT remove the nospam from the repy to address above,
instead send email to o1tech(at)skyenet(dot)net
JAPN 8_(
------------------------------
Date: Thu, 18 Jan 2001 07:51:19 -0000
From: "Trevor Ward" <tward10@jaguar.com>
Subject: Re: Perl/IIS and open()
Message-Id: <94679o$hig7@eccws12.dearborn.ford.com>
Perl doesn't work the same as the Web browser. It won't resolve Unix paths
on a windows box. or at least thats my theory.
However work relevant to your current path so you have c:\web\site\cgi-bin
as your current path
and you data files are in c:\web\site\data all you do is $filename =
'../data/logs.txt';
Well hope this helps
John Woltman <jew208@psu.edu> wrote in message
news:tPo96.125$cN.6302@bgtnsc07-news.ops.worldnet.att.net...
> I tried giving the CGI script the full path name (d:/www/log/log.txt) and
it
> worked. But I don't know the full path on the production server. I
*know*
> the path is correct because if I use the same script to generate a link to
> the log file then the link works.
> like this:
> $filename = "/logs/log.txt";
> print "<a href=\"$filename\">link</a>"; # takes me to correct file
> open (HFILE, $filename); #bombs.
> This is the error code I get when I include an "or die" for the open()
> statement.
> error opening /logs/log.txt: No such file or directory
> The file *does* exist, but I don't know what else the problem could be.
> Could it be something else?
> Thanks for your help so far.
> - John Woltman
>
> "Ron Grabowski" <ronnie@catlover.com> wrote in message
> news:3A6611E0.F13291F8@catlover.com...
> > > open(hFile, $filename);
> >
> > You are not checking for errors. Perhaps you are in the wrong directory.
> > Also try chdir('c:/winnt/system32/logfiles/'); or something similiar.
> >
> > open( HFILE, $filename) or die("error opening $filename: $!");
> >
> > >
> > > for $line ( <hFile>)
> > > {
> > > print $line;
> > > }
> >
> > print <HFILE>;
> >
> > - Ron
>
>
------------------------------
Date: Thu, 18 Jan 2001 14:01:14 GMT
From: tadmc@augustmail.com (Tad McClellan)
Subject: Re: Pulling KEy out of hash
Message-Id: <slrn96dj5v.4k2.tadmc@tadmc26.august.net>
Garry Williams <garry@zvolve.com> wrote:
>On Thu, 18 Jan 2001 00:24:26 -0600, John Michael <johnm@acadiacom.net>
>wrote:
>> $value =~ s/<!--(.|\n)*-->//g;
>
> $value =~ s/<!--.*-->//gs;
>Is this a CGI program? I rarely write CGI programs, but when I do, I
>use the CGI module. That way, I don't have to worry about making
^^^^^^
>mistakes converting entities and parsing keywords from a query.
^^^^^^^^
Like the mistakes in both of the above :-)
1) fails for:
<!-- first comment -->
<p>good stuff here</p>
<!-- second comment -->
2) fails for:
<!-- first comment -- >
(browsers get that second one wrong too!)
so then:
$value =~ s/<!--.*?--\s*>//gs;
and that _still_ isn't good enough...
Let's stop right now and just use a module where all (hopefully)
of these niggling details have already been discovered and
handled :-)
>>##Then I use the @config_vars array like so to fill in the values on
>>templates.
There are several modules that will do the templating for you.
Why reinvent that code too? Just use it.
--
Tad McClellan SGML consulting
tadmc@augustmail.com Perl programming
Fort Worth, Texas
------------------------------
Date: Thu, 18 Jan 2001 03:16:15 -0500
From: "James Kauzlarich" <nospam-abuse@[127.0.0.1]>
Subject: Re: Random text script, got one?:-)
Message-Id: <IHx96.4494$d25.28616@newsfeed.slurp.net>
----- Original Message -----
From: <johnstarr2001@my-deja.com>
Newsgroups: comp.lang.perl.misc
Sent: Tuesday, January 16, 2001 11:08 PM
Subject: Random text script, got one?:-)
> Hi I looking for a random text script if someone has already have made.
> Thanks.
Yeah. 2nd functional perl program I ever wrote. It was easy.
1) Buy (or borrow) a book on learning perl.
2) Read the sections on reading files.
3) Create a text file full of neat saying. (Or ads or whatever.)
4) Using the knowledge gained in part 2 write a program that reads a random
line of text from your file and print it.
or perhaps you meant:
#! \usr\bin\perl -w
use strict;
for ( $a = 1; $a <= int(rand(101)+1); $a++) {
print chr(int(rand(95)+32));
}
do NOT remove the nospam from the repy to address above,
instead send email to o1tech(at)skyenet(dot)net
JAPN 8_(
------------------------------
Date: Thu, 18 Jan 2001 14:01:12 GMT
From: tadmc@augustmail.com (Tad McClellan)
Subject: Re: regular expression question. pls help
Message-Id: <slrn96dfal.4k2.tadmc@tadmc26.august.net>
Paul Sack <paul-sackun@jefe.eyep.net> wrote:
>In article <9454hp$mdd$1@nnrp1.deja.com>, vupt@yahoo.com wrote:
>><item delimiter=", " name="UPT
>>PIR"><value>http://www.uptpir.com/products/index.html</value></item>
>>
>>my $matchKey="UPT PIR[ .]*?<value>(.*)</value>";
>> if ($line=~/$matchKey/) {
>So what's the problem you are having?
The pattern fails to match the string. He wants it to succeed, not fail.
[ use PSI::ESP;
I'd guess the real problem is that the OP expects dot to match
any character, but dot is not meta when used in a char class.
]
--
Tad McClellan SGML consulting
tadmc@augustmail.com Perl programming
Fort Worth, Texas
------------------------------
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 88
*************************************