[19918] in Perl-Users-Digest
Perl-Users Digest, Issue: 2113 Volume: 10
daemon@ATHENA.MIT.EDU (Perl-Users Digest)
Mon Nov 12 03:10:46 2001
Date: Mon, 12 Nov 2001 00:10:18 -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: <1005552618-v10-i2113@ruby.oce.orst.edu>
Content-Type: text
Perl-Users Digest Mon, 12 Nov 2001 Volume: 10 Number: 2113
Today's topics:
Re: Exec stops execution of Perl script after having co <comdog@panix.com>
Re: Exec stops execution of Perl script after having co <uri@stemsystems.com>
Re: Exec stops execution of Perl script after having co <mgjv@tradingpost.com.au>
flat text database cgi (rumi_red)
Re: flat text database cgi (Logan Shaw)
Re: flat text database cgi <echang@netstorm.net>
Re: How to assign initial value to variable? <spamfree@go-away.net>
Re: How to assign initial value to variable? <c_clarkson@hotmail.com>
Re: How to initialise EOF (W) <spamfree@go-away.net>
Re: How to initialise EOF (W) (Garry Williams)
Re: IO::Socket write fail <uri@stemsystems.com>
Re: Perl vs. Active Perl <randy@theory.uwinnipeg.ca>
References and EasyTree, getting data back <danny@lennon.postino.com>
Re: References and EasyTree, getting data back (Tad McClellan)
Re: References and EasyTree, getting data back <mgjv@tradingpost.com.au>
Re: Regular Expressions <goldbb2@earthlink.net>
Re: Removing whitespace from list / array (mark)
Reserve memory for array? <markus.cl@gmx.de>
Re: Reserve memory for array? <Tassilo.Parseval@post.rwth-aachen.de>
Re: self-printing perl program (Tramm Hudson)
SMTP issue (Sandy Keathley)
Re: SMTP issue <andrew@erlenstar.demon.co.uk>
Re: Software error with -T using sendmail <spamfree@go-away.net>
Re: Software error with -T using sendmail (Garry Williams)
Re: Sorting an array - help please <goldbb2@earthlink.net>
Re: sorting hashes == headaches (Greg Backus)
sorting qestion <sudhir@newmail.net>
Re: sorting qestion <Tassilo.Parseval@post.rwth-aachen.de>
timeout of system(sudo prog) using AlarmCall messes up (Phil)
Re: Unencoding <geoff@REMOVETHISgeoffball.net>
Re: Unencoding <geoff@REMOVETHISgeoffball.net>
Digest Administrivia (Last modified: 6 Apr 01) (Perl-Users-Digest Admin)
----------------------------------------------------------------------
Date: Sun, 11 Nov 2001 18:26:30 -0500
From: brian d foy <comdog@panix.com>
Subject: Re: Exec stops execution of Perl script after having completed?????
Message-Id: <comdog-0F5DB7.18263011112001@news.panix.com>
In article <9smocl$148as7$1@ID-98646.news.dfncis.de>, "Bob Rock"
<no_spam.yet_another_apprentice@hotmail.com> wrote:
> I recently noticed that the system and exec calls are not equivalent.
that's why you read the documentation before you use new functions. :)
--
brian d foy <comdog@panix.com> - Perl services for hire
CGI Meta FAQ - http://www.perl.org/CGI_MetaFAQ.html
Troubleshooting CGI scripts - http://www.perl.org/troubleshooting_CGI.html
------------------------------
Date: Mon, 12 Nov 2001 06:05:05 GMT
From: Uri Guttman <uri@stemsystems.com>
Subject: Re: Exec stops execution of Perl script after having completed?????
Message-Id: <x7r8r4ldzw.fsf@home.sysarch.com>
>>>>> "bdf" == brian d foy <comdog@panix.com> writes:
bdf> In article <9smocl$148as7$1@ID-98646.news.dfncis.de>, "Bob Rock"
bdf> <no_spam.yet_another_apprentice@hotmail.com> wrote:
>> I recently noticed that the system and exec calls are not equivalent.
bdf> that's why you read the documentation before you use new functions. :)
this brings up the question of why the OP ever thought they would be
equivilent? why would perl have exec and system be synonyms? the fact
that they both deal with external programs and have different names
should trigger a bell that they might be related but different? we get
the same thing with confusion between backticks and system. newbies
think 'run a process' and don't catch the critical difference of where
the stdout goes to.
so in general, rtfm always but especially when you think 2 perl
ops/funcs are similar to learn how they are different.
uri
--
Uri Guttman ------ uri@stemsystems.com -------- http://www.stemsystems.com
-- Stem is an Open Source Network Development Toolkit and Application Suite -
----- Stem and Perl Development, Systems Architecture, Design and Coding ----
Search or Offer Perl Jobs ---------------------------- http://jobs.perl.org
------------------------------
Date: Mon, 12 Nov 2001 18:39:41 +1100
From: Martien Verbruggen <mgjv@tradingpost.com.au>
Subject: Re: Exec stops execution of Perl script after having completed?????
Message-Id: <slrn9uuv5t.f5j.mgjv@martien.heliotrope.home>
[removed alt.perl]
On Mon, 12 Nov 2001 06:05:05 GMT,
Uri Guttman <uri@stemsystems.com> wrote:
>>>>>> "bdf" == brian d foy <comdog@panix.com> writes:
>
> bdf> In article <9smocl$148as7$1@ID-98646.news.dfncis.de>, "Bob Rock"
> bdf> <no_spam.yet_another_apprentice@hotmail.com> wrote:
>
> >> I recently noticed that the system and exec calls are not equivalent.
>
> bdf> that's why you read the documentation before you use new functions. :)
>
> this brings up the question of why the OP ever thought they would be
> equivilent? why would perl have exec and system be synonyms?
> so in general, rtfm always but especially when you think 2 perl
> ops/funcs are similar to learn how they are different.
As in the difference between y/// and tr///? or for and foreach?
;)
Martien
--
|
Martien Verbruggen | If it isn't broken, it doesn't have
| enough features yet.
|
------------------------------
Date: 11 Nov 2001 22:25:31 -0800
From: rumi_red@yahoo.com (rumi_red)
Subject: flat text database cgi
Message-Id: <4af158c4.0111112225.10fab000@posting.google.com>
Hi!
I'm looking for a sample script that illustrates how to make a flat
text database cgi script.
On a web page, I want a user to be able to enter the following
information
a) name
b) date
c) house
d) color
And on the same page, have a user be able to perform a query on the
following fields as well.
I have search the net so far for possible sample scripts and I have
several PERL books but none illustrate how to make a flat text
database for the web.
Please help if you can and thanks so much!!!
------------------------------
Date: 12 Nov 2001 00:36:52 -0600
From: logan@cs.utexas.edu (Logan Shaw)
Subject: Re: flat text database cgi
Message-Id: <9snqm4$cbb$1@charity.cs.utexas.edu>
In article <4af158c4.0111112225.10fab000@posting.google.com>,
rumi_red <rumi_red@yahoo.com> wrote:
>I have search the net so far for possible sample scripts and I have
>several PERL books but none illustrate how to make a flat text
>database for the web.
I don't see how a flat text database can be "for the web". Either it's
a flat text database or not. Whether its contents are displayed on
the web or not is a separate issue, as far as I can see.
Anyway, if you really want to do this, you'll need to do the
following things:
1) Make sure your CGI script actually has access to read/write
some file somewhere.
2) Learn to lock your file with lockf() when doing updates, so that
two simultaneously-running CGI scripts don't screw up the file and
cause you to lose data.
3) Come up with a file format that you want to use, and writes
some routines to parse and generate entries in this format.
4) Learn to append to a file, so that you can add new entries
to the database. (I'm assuming you don't need to modify existing
entries or delete entries.)
"perldoc -f lockf" should help you with #2, and "perldoc -f open"
should help you with #4.
- Logan
--
"In order to be prepared to hope in what does not deceive,
we must first lose hope in everything that deceives."
Georges Bernanos
------------------------------
Date: Mon, 12 Nov 2001 07:17:10 GMT
From: "E.Chang" <echang@netstorm.net>
Subject: Re: flat text database cgi
Message-Id: <Xns9157184839BA0echangnetstormnet@207.106.92.86>
logan@cs.utexas.edu (Logan Shaw) wrote in
news:9snqm4$cbb$1@charity.cs.utexas.edu:
> In article <4af158c4.0111112225.10fab000@posting.google.com>,
> rumi_red <rumi_red@yahoo.com> wrote:
[good advice snipped]
> "perldoc -f lockf" should help you with #2, and "perldoc -f open"
> should help you with #4.
$ perldoc -f lockf
No documentation for perl function `lockf' found
I think you meant
"perldoc -f flock"
--
EBC
------------------------------
Date: Mon, 12 Nov 2001 01:45:51 GMT
From: "spamfree" <spamfree@go-away.net>
Subject: Re: How to assign initial value to variable?
Message-Id: <jRFH7.30035$mh1.3645678@news1.cableinet.net>
"E.Chang" <echang@netstorm.net> wrote in message
news:Xns9156A06C34EB4echangnetstormnet@207.106.92.86...
> "spamfree" <spamfree@go-away.net> wrote in
> news:4AAH7.28072$mh1.3448798@news1.cableinet.net:
>
> >> >> use strict;
> >> >I get software server error with strict.
> [snip]
>
> >> You should do all of your initial testing from the command line.
> >> Even better if it is on your own computer rather than an ISP's
> >> 'puter.
> > Hmm, I don't know how to enter name=value pairs standard input
> > (keyboard) in offline mode using active perl for windows, and I get
>
> When you get the CGI.pm the prompt for name=value pairs, type in the
> name and value pairs you want to initialize in the form name=value, one
> pair per line. End with control-D (Unix) or control-Z (DOS).
AH! I wasn't aware of the control-Z for DOS.
>
> > "Too late for T option line one but.. I'll read the docs some more
> > :-)
>
> To avoid the "Too late..." error, invoke your program with the -T
> switch on the command line. "perl -T scriptname"
I've read persec and discovered that I needed to untaint an open pipe call:
$ENV{PATH} = "/usr/sbin/sendmail";
delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};
open (MAIL, "|/usr/sbin/sendmail -t") || &ErrorMessage;
>
> [snip]
>
> >> Because you have surely looked for Perl FAQs that mention CGI:
> >>
> >> perldoc -q CGI
> >>
> >> "How can I get better error messages from a CGI program?"
> >> Yup.The very first thing I did.
>
> And did you follow the advice? Did you add
>
> use CGI::Carp qw(fatalsToBrowser);
>
> as the first statement after the shebang line?
As I said, it was the first thing I did.
> [snip]
>
> BTW, it is impossible to tell whose good advice you are responding to
> above. When you follow-up to an article, don't delete the attribution
> line.
>
Thanks
------------------------------
Date: Sun, 11 Nov 2001 20:35:34 -0000
From: "Charles K. Clarkson" <c_clarkson@hotmail.com>
Subject: Re: How to assign initial value to variable?
Message-Id: <tuuesd962rnve2@corp.supernews.com>
"spamfree" <spamfree@go-away.net> wrote:
in message
news:mD1G7.3931$3N6.574743@news1.cableinet.net...
: #!/usr/bin/perl -Tw
: use diagnostics;
: use CGI qw(:standard);
: use CGI::Carp qw(fatalsToBrowser);
:
: Use of uninitialized value at
:
/home/sites/site13/web/cgi-bin/pre-register/pre-register.pl
: line 139 (#1)
: (W) An undefined value was used as if it were already
: defined. It was interpreted as a "" or a 0, but maybe
: it was a mistake. To suppress this warning assign an
: initial value to your variables. [Wed Nov 7 03:05:59
: 2001]
: pre-register.pl: Use of uninitialized value at
:
/home/sites/site13/web/cgi-bin/pre-register/pre-register.pl
: line 139.
:
: <cut>
:
[added some editing]
: sub check_data{
:
: if ($firstname =~ tr/a-zA-Z\n\t //c) {
: $errormessage = "Special characters are forbidden. You
: used one in the firstname field.
";
: &errorpage;
: exit;
: }
: {
: $errormessage = 'The FIRSTNAME field is restricted to
: Max = 50 characters including spaces!'
: if length $firstname > 50;
: &errorpage;
: exit;
: }
:
[snipped comment]
:
: if ( $surname =~ tr/a-zA-Z\n\t //c) {
: $errormessage = "Special characters are forbidden. You
: used one in the surname field. ";
: &errorpage;
: exit;
: }
: {
: $errormessage = 'The SURNAME field is restricted to
: Max = 50 characters including spaces!'
: if length $surname > 50;
: &errorpage;
: exit;
: }
:} [added]
:
:
: sub errorpage{
:
: print "Content-type: text/html", "\n\n";
:
: print <<EOF; #Line 139
As written above your sub will sometimes call
errorpage() without a value in $errormessage. You
can avoid this by never relying on variables from
outside a sub.
:
: <html>
: <head>
: <title>ERROR!</title>
: </head>
: <body bgcolor="#FFFFFF">
: <h1>We are sorry!</h1>
: <p>The form was not filled in correctly.</p>
: Here is the problem: <b>$errormessage</b>
: <p>
: Please use the "back button" of your browser to
: return to the form and correct the mistake.
: <p>
: <font color="656565"><i><b>admin\@mydomain.com
: </b></i></font>
: </body>
: </html>
: EOF
: }
:
Now, I have some questions. Why load the :standard
subs from CGI.pm and use a HERE document:
: use CGI qw(:standard);
[snip]
: print <<EOF; #Line 139
:
: <html>
: <head>
: <title>ERROR!</title>
: </head>
: <body bgcolor="#FFFFFF">
: <h1>We are sorry!</h1>
: <p>The form was not filled in correctly.</p>
: Here is the problem: <b>$errormessage</b>
: <p>
: Please use the "back button" of your browser to
: return to the form and correct the mistake.
: <p>
: <font color="656565"><i><b>admin\@mydomain.com
: </b></i></font>
: </body>
: </html>
: EOF
: }
Why not:
sub error_page {
my $error_message = shift;
$error_message ||= 'unknown error.';
print
header,
start_html(-title => 'ERROR!',-bgcolor => '#FFFFFF'),
h1('We are sorry!'),
p('The form was not filled in correctly.'),
'Here is the problem: ', b($error_message),
p('Please use the "back button" of your browser to',
'return to the form and correct the mistake.'),
p( font( {-color => 656565}, i(
b('admin@mydomain.com') ) ) ),
end_html;
exit;
}
And why assign $errormessage and not pass it with
errorpage? In fact, why are you instead explicitly
making @_ visible by using '&errorpage'?
: if ( $surname =~ tr/a-zA-Z\n\t //c) {
: $errormessage = "Special characters are forbidden. You
: used one in the surname field. ";
: &errorpage;
: exit;
: }
error_page('Special characters are forbidden. You
used one in the SURNAME field.')
if $surname =~ tr/a-zA-Z\n\t //c;
------------------------------
Date: Mon, 12 Nov 2001 01:46:57 GMT
From: "spamfree" <spamfree@go-away.net>
Subject: Re: How to initialise EOF (W)
Message-Id: <lSFH7.30043$mh1.3646569@news1.cableinet.net>
"Michael Budash" <mbudash@sonic.net> wrote in message
news:mbudash-3BF5B8.12502111112001@news.sonic.net...
> In article <5AAH7.28073$mh1.3449816@news1.cableinet.net>, "spamfree"
> <spamfree@go-away.net> wrote:
>
> > Warning (W)
> > Use of uninitialized value at
> > /home/sites/site13/web/cgi-bin/pre-register/pre-register.pl line 166.
> > print <<EOF; # line 166
> >
> > How to initialize EOF line?
>
> often the line specified in an error message is confusing... as in this
> case... there's nothing wrong with this line... can we see the 5 lines
> before and after?
>
Here's more lines...
my $run = param("run");
if ($run =~ /Submit/i){
&check_data;
&errorpage;
#etc
}
sub check_data{
if ($firstname =~ tr/a-zA-Z' //c) { #allows alphabetic, apostrophy, and
spaces only
$errormessage = "Special characters are forbidden. You used one in the
FIRSTNAME field. ";
errorpage();
exit;
}
if (length ($firstname) > 50) {
$errormessage = 'The FIRSTNAME field is restricted to Max = 50
characters including spaces!' ;
errorpage();
exit;
}
#more error checking
}#end of sub check_data
sub errorpage{
print "Content-type: text/html", "\n\n";
print<<EOF; # This is line 166
<html>
<head>
<title>ERROR!</title>
</head>
<body bgcolor="#FFFFFF">
<h1>We are sorry!</h1>
<p>The form was not filled in correctly.</p>
Here is the problem: <b>$errormessage</b>
<p>
Please use the "back button" of your browser to return to the form and
correct the mistake.
<p>
<font color="656565"><i><b>admin\@mydomain.com</b></i></font>
</body>
</html>
EOF
}end of sub errorpage
#$errormessage follows etc.
--
millside
_____________
------------------------------
Date: Mon, 12 Nov 2001 03:57:56 GMT
From: garry@ifr.zvolve.net (Garry Williams)
Subject: Re: How to initialise EOF (W)
Message-Id: <slrn9uui66.2ia.garry@zfw.zvolve.net>
On Mon, 12 Nov 2001 01:46:57 GMT, spamfree <spamfree@go-away.net> wrote:
[ snip ]
> sub errorpage{
>
> print "Content-type: text/html", "\n\n";
>
>
> print<<EOF; # This is line 166
>
> <html>
> <head>
> <title>ERROR!</title>
> </head>
> <body bgcolor="#FFFFFF">
> <h1>We are sorry!</h1>
> <p>The form was not filled in correctly.</p>
> Here is the problem: <b>$errormessage</b>
> <p>
> Please use the "back button" of your browser to return to the form and
> correct the mistake.
> <p>
> <font color="656565"><i><b>admin\@mydomain.com</b></i></font>
> </body>
> </html>
>
> EOF
>
> }end of sub errorpage
> #$errormessage follows etc.
Well, I guess that last bit is a compile-time error. But I suppose
that's because something wasn't copy/pasted, but typed instead.
The warning you are receiving is evidentally because $errormessage is
uninitialized.
How does $errormessage get set prior to calling this subroutine? Why
don't you pass in its value instead of relying on a global variable?
--
Garry Williams
------------------------------
Date: Mon, 12 Nov 2001 06:27:38 GMT
From: Uri Guttman <uri@stemsystems.com>
Subject: Re: IO::Socket write fail
Message-Id: <x7n11slcy9.fsf@home.sysarch.com>
>>>>> "M" == Mark <admin@asarian-host.net> writes:
M> for (;;) {
M> foreach $client ($sel -> can_read (0.1)) {
M> if ($client == $sock) {
M> $client = $sock -> accept ();
M> $sel -> add ($client);
M> nonblock ($client);
M> } else {
M> my $input;
M> my $got = $client -> recv ($input, POSIX::BUFSIZ, 0);
M> unless (defined ($got) && length ($input)) {
M> disconnect ($client);
M> next;
M> }
M> $inbuffer{$client} .= $input;
M> push (@{$ready{$client}}, $2) while ($inbuffer{$client} =~
M> s/(<command>((.|\n)*?)<\/command>\n)//m);
M> }
M> }
M> foreach $client (keys %ready) {
here is your problem. keys of a hash can only be strings. you are using
a socket (which is a glob ref) for a key and it is being converted to a
string. it can't be converted back into a proper ref. so keys is
returning the stringified socket refs which are not useful to you. one
solution is to make your %ready hash have hashes as values (called a
hash of hashes) and store in them the buffer AND the real
socket. another solution is to keep a separate hash of sockets
(stringified ref) to sockets (real ref).
uri
--
Uri Guttman ------ uri@stemsystems.com -------- http://www.stemsystems.com
-- Stem is an Open Source Network Development Toolkit and Application Suite -
----- Stem and Perl Development, Systems Architecture, Design and Coding ----
Search or Offer Perl Jobs ---------------------------- http://jobs.perl.org
------------------------------
Date: Sun, 11 Nov 2001 20:56:17 -0600
From: "Randy Kobes" <randy@theory.uwinnipeg.ca>
Subject: Re: Perl vs. Active Perl
Message-Id: <9snege$1r9$1@canopus.cc.umanitoba.ca>
"Daniel Berger" <djberg96@hotmail.com> wrote in message
news:cIbH7.2623$T6.111836@typhoon.mn.mediaone.net...
>
> There *used* to be PerlMagic for Win32, which was basically a free distro
> for Win32. These were the same folks that made the CodeMagic IDE.
However,
> after just checking codemagiccd.com, it looks like they're defunct.
That's
> too bad because that IDE really had potential (it sure was a helluva lot
> better than Komodo).
As Tim noted, there's a Win32 perl binary on CPAN at
http://www.cpan.org/authors/id/G/GR/GRAHAMC/
that's distributed under the terms of either the GNU
General Public License or the Artistic License. Also, we
have a perl/Apache/mod_perl/mod_ssl binary at
ftp://theoryx5.uwinnipeg.ca/pub/other/
that's distributed under the same terms.
> For a scathing commentary on ActiveState Perl (and its licensing), see
> www.petes-place.com.
One may not like the licensing terms, but to be balanced, ActiveState
has done a lot to merge the Win32 Perl port into the mainstream.
As well, their binaries and, particularly, their ppm utility, has made
Perl more accessible in the Win32 world, especially since a user
often in this environment isn't all that familiar with C compilers.
best regards,
randy kobes
------------------------------
Date: Mon, 12 Nov 2001 02:28:41 GMT
From: Danny Aldham <danny@lennon.postino.com>
Subject: References and EasyTree, getting data back
Message-Id: <9snbmb$kgt$1@lennon.postino.com>
I am truly weak with references, so I avoid them when possible, but
today I started using what looks like a great tool, the XML parser
module XML::Parser::EasyTree . It is parsing the xml docs I have
great, and creates a wonderful hash that I can look at if I dump
the data using Data::Dumper , but I cannot figure out how to look
at the data with a program.
So far I have :
my $tree = $parse ->parsefile('/tmp/myfile.xml') ;
foreach $key (keys (%$tree) {
print "Key : $key \n"; #Which works, giving me 4 keys
# attrib , content , type , name
print "$key => $tree->{$key} \n"; # Which fails
# with errors like "e" isn't numberic
# or bad index coercing array into hash
}
I am trying to write a simple program that will toggle thru all the keys
and values, so I can better understand how to access the data.
Hope this is clear, any suggestions are appreciated.
--
Danny Aldham Providing Certified Internetworking Solutions to Business
www.postino.com E-Mail, Web Servers, Web Databases, SQL PHP & Perl
------------------------------
Date: Mon, 12 Nov 2001 04:32:56 GMT
From: tadmc@augustmail.com (Tad McClellan)
Subject: Re: References and EasyTree, getting data back
Message-Id: <slrn9uugpp.5i4.tadmc@tadmc26.august.net>
Danny Aldham <danny@lennon.postino.com> wrote:
>So far I have :
>
>foreach $key (keys (%$tree) {
^ ^ ^
^ ^ ^
Please post your real code.
--
Tad McClellan SGML consulting
tadmc@augustmail.com Perl programming
Fort Worth, Texas
------------------------------
Date: Mon, 12 Nov 2001 05:27:39 GMT
From: Martien Verbruggen <mgjv@tradingpost.com.au>
Subject: Re: References and EasyTree, getting data back
Message-Id: <slrn9uunf0.2q5.mgjv@verbruggen.comdyn.com.au>
On Mon, 12 Nov 2001 02:28:41 GMT,
Danny Aldham <danny@lennon.postino.com> wrote:
> I am truly weak with references, so I avoid them when possible, but
> today I started using what looks like a great tool, the XML parser
> module XML::Parser::EasyTree . It is parsing the xml docs I have
> great, and creates a wonderful hash that I can look at if I dump
> the data using Data::Dumper , but I cannot figure out how to look
> at the data with a program.
> So far I have :
>
> my $tree = $parse ->parsefile('/tmp/myfile.xml') ;
> foreach $key (keys (%$tree) {
That can't compile. You're sure that this is your real code? Next
time, please make sure to post a piece of code that at least compiles.
Besides that, the documentation for XML::Parser::EasyTree says that
$tree is an array reference, so you can't treat it like a hash
reference.
You probably need to write a recursive subroutine to be able to deal
with this tree. This subroutine would have to deal with the node at
hand (an array reference) and depending on the type of the node
perform some action, which only you know about.
The following example program reads an XML document, and prints out an
equivalent one (Note that this one doesn't recreate empty nodes like
<ref /> the same way, but instead outputs them like <ref></ref>, which
is equivalent anyway):
#!/usr/local/bin/perl -w
use strict;
use XML::Parser;
use XML::Parser::EasyTree;
my $p=new XML::Parser(Style=>'EasyTree');
my $tree=$p->parse(\*DATA);
print_easy_tree($tree);
sub print_easy_tree
{
my $node = shift;
for my $element (@$node)
{
if ($element->{type} eq 'e')
{
print "<$element->{name}>";
print_easy_tree($element->{content});
print "</$element->{name}>";
}
elsif ($element->{type} eq 't')
{
print $element->{content};
}
else
{
print "[IGNORED $element->{type}]";
}
}
}
__DATA__
<foo>
<head id="a">Hello <em>there</em>
</head>
<bar>Howdy<ref/>
</bar>
do
</foo>
A more elegant solution would probably set up a dispatch table to be
called, something like:
#!/usr/local/bin/perl -w
use strict;
use XML::Parser;
use XML::Parser::EasyTree;
my $p=new XML::Parser(Style=>'EasyTree');
my $tree=$p->parse(\*DATA);
my %dispatch = ( e => \&element_print, t => \&text_print );
print_easy_tree($tree);
## Element subroutines
sub element_print
{
print "<$_[0]->{name}>";
print_easy_tree($_[0]->{content});
print "</$_[0]->{name}>";
}
sub text_print { print $_[0]->{content} }
sub ignore_element { print "[IGNORED $_[0]->{type}]" }
## Node handler
sub print_easy_tree
{
my $node = shift;
for my $element (@$node)
{
my $ref = $dispatch{$element->{type}} || \&ignore_element;
$ref->($element);
}
}
__DATA__
<foo>
<head id="a">Hello <em>there</em>
</head>
<bar>Howdy<ref/>
</bar>
do
</foo>
Pick whichever method is most natural to you (I'd suggest giving the
dispatch one a chance first, because it is a bit more elegant and
modular).
Martien
PS. If you'd like to have a print routine that does print <ref /> for
empty tags:
sub element_print
{
if (@{$_[0]->{content}})
{
print "<$_[0]->{name}>";
print_easy_tree($_[0]->{content});
print "</$_[0]->{name}>";
}
else
{
print "<$_[0]->{name}/>";
}
}
--
|
Martien Verbruggen |
Trading Post Australia Pty Ltd | What's another word for Thesaurus?
|
------------------------------
Date: Sun, 11 Nov 2001 22:01:52 -0500
From: Benjamin Goldberg <goldbb2@earthlink.net>
Subject: Re: Regular Expressions
Message-Id: <3BEF3BA0.FE169F7C@earthlink.net>
Anya Miretsky wrote:
>
> I am new to Perl, so therefore the simple question..
>
> How do I use a regular expression to make all uppercase letters in a
> string into lowercase?
s/([[:upper:]]+)/\L$1\E/g;
--
Klein bottle for rent - inquire within.
------------------------------
Date: 12 Nov 2001 00:03:41 -0800
From: mark.adaoui@siemens.at (mark)
Subject: Re: Removing whitespace from list / array
Message-Id: <487f3b0f.0111120003.78d32a7@posting.google.com>
Thanx Tad McClellan & Jason Kelley,
Without your help, this prob would have taken me a while to solve,
once again thanx a lot for the help that both of you provided.
Though i will admit that Tad's solution was the simpler of the 2 to understand.
Thankyou from Mark the happier Perl diver.
------------------------------
Date: Mon, 12 Nov 2001 01:10:55 +0100
From: "Markus Dehmann" <markus.cl@gmx.de>
Subject: Reserve memory for array?
Message-Id: <9sn43j$147j04$1@ID-101658.news.dfncis.de>
Can I reserve memory for an array when I know about how much memory it will
need in the end?
If there is a lot to store and it is pushed step by step, it must be much
more efficient to say when you initialize the array, okay, it will need
about 10MB and not allocate a little bit each time the push command is
given..
------------------------------
Date: Mon, 12 Nov 2001 01:31:38 +0100
From: "Tassilo v. Parseval" <Tassilo.Parseval@post.rwth-aachen.de>
Subject: Re: Reserve memory for array?
Message-Id: <9sn59a$85a$07$1@news.t-online.com>
On Mon, 12 Nov 2001 01:10:55 +0100, Markus Dehmann wrote:
> Can I reserve memory for an array when I know about how much memory it will
> need in the end?
>
> If there is a lot to store and it is pushed step by step, it must be much
> more efficient to say when you initialize the array, okay, it will need
> about 10MB and not allocate a little bit each time the push command is
> given..
It may be more efficient but that's debatable. There is the trick of
assigning to $#array.
my @a;
$#a = 10000000;
This eats about 40meg of memory on my machine. You can experiment a
little with the number. According to top '$#a = 2500000;' needs quite
exactly 10meg.
Tassilo
--
Boston State House is the hub of the Solar System. You couldn't pry that out
of a Boston man if you had the tire of all creation straightened out for a
crowbar.
-- Oliver Wendell Holmes
------------------------------
Date: 11 Nov 2001 23:04:21 GMT
From: hudson@swcp.com (Tramm Hudson)
Subject: Re: self-printing perl program
Message-Id: <9sn05l$baf$1@sloth.swcp.com>
[ Posted and cc'd to cited author ]
Charles Blair <c-blair@uiuc.edu> wrote:
> ... What is the shortest perl program that will
> print itself? ...
An empty file is a valid Perl program and prints itself. You
would be very hard pressed to produce a shorter version.
For non-pathological cases there are several interesting examples.
Uri suggested a good search term ("quine", from Hofstadter),
although my first try with Google produced several good examples:
http://www.google.com/search?q=self+printing+perl+program
I'm not sure how much less cursory you could be.
Trammell
--
o hudson@swcp.com O___|
/|\ http://www.swcp.com/~hudson/ M 240.476.1373 /\ \_
<< KC5RNF H 505.315.5133 \ \/\_\
0 U \_ |
------------------------------
Date: Mon, 12 Nov 2001 02:31:53 GMT
From: skeath@keathleywebs.com (Sandy Keathley)
Subject: SMTP issue
Message-Id: <tuu62hbskqq420@corp.supernews.com>
In sending email through an SMTP server (using Socket), a typical code
snippet is
print SOCK "mail from: <", $send_to[2], "> $CRLF";
print SOCK "RCPT To: $send_to[1] $CRLF";
print SOCK "data$CRLF";
print SOCK "To: $send_to[0] <$send_to[1]>", $CRLF;
print SOCK "From: $send_to[2]",$CRLF;
print SOCK "Reply-to: $send_to[3]",$CRLF;
By default, the RCPT command sends an email to the "From" address in
the event of failure. According to the O'Reilly book on Internet
Email (Wood), RCPT can take the argument NOTIFY=SUCCESS
to send an email in the event of success:
print SOCK "RCPT To: $send_to[1] NOTIFY=SUCCESS $CRLF";
but when this code is inserted, no receipts are generated at all, even
for failure. The Notify argument is supposed to be added also to the
MAIL command, and it may be necessary to change HELO to EHLO to
activate the ESMTP features, but that is unclear.
Has anyone dealt with generating receipts for success from a Perl
script?
Sandy Keathley <skeath@keathleywebs.com>
------------------------------
Date: 12 Nov 2001 00:44:59 +0000
From: Andrew Gierth <andrew@erlenstar.demon.co.uk>
Subject: Re: SMTP issue
Message-Id: <87ofm8rf5g.fsf@erlenstar.demon.co.uk>
>>>>> "Sandy" == Sandy Keathley <skeath@keathleywebs.com> writes:
Sandy> In sending email through an SMTP server (using Socket), a
Sandy> typical code snippet is
Sandy> print SOCK "mail from: <", $send_to[2], "> $CRLF";
then you need to check the response from the server
Sandy> print SOCK "RCPT To: $send_to[1] $CRLF";
Missing <>, and again you need to check the response
Sandy> print SOCK "data$CRLF";
another check needed here
Sandy> By default, the RCPT command sends an email to the "From"
Sandy> address in the event of failure.
Unless, of course, the RCPT command itself fails, in which case no
email is sent anywhere.
Sandy> According to the O'Reilly book on Internet Email (Wood), RCPT
Sandy> can take the argument NOTIFY=SUCCESS to send an email in the
Sandy> event of success:
Only if you negotiated ESMTP (using EHLO), and then only if the remote
server supports DSNs.
If you're going to do your own implementations of Internet protocols,
then you need to actually read the specifications. Otherwise, stick
to using existing modules.
--
Andrew.
------------------------------
Date: Mon, 12 Nov 2001 01:47:05 GMT
From: "spamfree" <spamfree@go-away.net>
Subject: Re: Software error with -T using sendmail
Message-Id: <tSFH7.30044$mh1.3646512@news1.cableinet.net>
> >> I wish to enable taint but get software error opening sendmail.
> >> Do I need to untaint path?
> >> If so, how to do that.
> >>
> >> #!/usr/bin/perl -Tw
> >> #<code cut>
> >> open (MAIL, "|/usr/sbin/sendmail -t") || &ErrorMessage;
> >> # Insecure $ENV{PATH} while running with -T switch ?
>
> Set $ENV{PATH} *before* opening a pipe to sendmail.
>
> See the perlsec manual page.
>
Thanks gary I did as you suggested and included this code from manpage:
$ENV{PATH} = "/usr/sbin/sendmail"; #Insecure $ENV{PATH} while running
with -T switch unless predefined
delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};
Everything appears to be working ok except for this second line:
delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};
It appears to be untainted and works just the same even with this line
missing?
Any ideas why this should be.. perlsec says
$path = $ENV{'PATH'}; # $path now tainted
$ENV{'PATH'} = '/bin:/usr/bin';
delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'
$path = $ENV{'PATH'}; # $path now NOT tainted
system "echo $data"; # Is secure now!
--
millside
_____________
------------------------------
Date: Mon, 12 Nov 2001 03:39:55 GMT
From: garry@ifr.zvolve.net (Garry Williams)
Subject: Re: Software error with -T using sendmail
Message-Id: <slrn9uuh4b.2ia.garry@zfw.zvolve.net>
On Mon, 12 Nov 2001 01:47:05 GMT, spamfree <spamfree@go-away.net> wrote:
>> >> I wish to enable taint but get software error opening sendmail.
>> >> Do I need to untaint path?
>> >> If so, how to do that.
>> >>
>> >> #!/usr/bin/perl -Tw
>> >> #<code cut>
>> >> open (MAIL, "|/usr/sbin/sendmail -t") || &ErrorMessage;
>> >> # Insecure $ENV{PATH} while running with -T switch ?
>>
>> Set $ENV{PATH} *before* opening a pipe to sendmail.
>>
>> See the perlsec manual page.
>>
> Thanks gary I did as you suggested and included this code from manpage:
> $ENV{PATH} = "/usr/sbin/sendmail"; #Insecure $ENV{PATH} while running
> with -T switch unless predefined
Your line-wrapping seems to be broken. The comment was wrapped and
will produce a compile error.
That is a strange path. You certainly have untainted the $ENV{PATH}
variable because you set it to some value. But it is a completely
useless value since `/usr/sbin/sendmail' is probably not a directory.
The PATH variable should be a colon-separated (:) list of directories.
Since the /usr/bin directory is generally a trusted directory, it is
often the value used when setting the PATH variable. But hey, I don't
know what your needs are. I just know that a PATH that isn't a
directory is useless.
> delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};
Deleting these variables is required under -T under some circumstances
because they can be used by some external programs in a (presumably)
trusted way.
> Everything appears to be working ok except for this second line:
> delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};
> It appears to be untainted and works just the same even with this line
> missing?
I assume you mean the PATH environment variable ($ENV{PATH}) is now
untainted.
This deleting of certain environment variables has nothing to do with
the value of the PATH variable. $ENV{PATH} is untainted because you
assigned it an untainted (constant) value.
Deleting or not deleting *other* environment variables will not affect
that.
> Any ideas why this should be.. perlsec says
> $path = $ENV{'PATH'}; # $path now tainted
>
> $ENV{'PATH'} = '/bin:/usr/bin';
> delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'
>
> $path = $ENV{'PATH'}; # $path now NOT tainted
> system "echo $data"; # Is secure now!
It's unfortunate that the manual has this sequence of examples. The
question of whether the variable $path is tainted in this example does
not in any way depend on the values of anything other than $ENV{PATH}.
The manual page is misleading.
Try to overlook the example.
But keep the delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'} statement
in scripts running under -T (that end up running programs with the
shell or referencing the current working directory with Cwd). Read
further (after your quoted example) in the perlsec manual page about
why you should delete these variables.
--
Garry Williams
------------------------------
Date: Sun, 11 Nov 2001 22:20:07 -0500
From: Benjamin Goldberg <goldbb2@earthlink.net>
Subject: Re: Sorting an array - help please
Message-Id: <3BEF3FE7.3F83F326@earthlink.net>
fred56 wrote:
>
> Hi
>
> I'v been working my way through the book O'Reilly book Learning perl
> and iv come up with a bit of code that allmost does what i want it to
> (See bellow)
>
> sub main {
>
> open(DATA, "< $file") or die "Can't open $file: $!"; #Open
> Database
> while (<DATA>) {
> ++$counter;
> @tabledata=split(/\s*\¶\s*/, $_);
[snip]
> what i want to be able to do is sort the array based on the third
> field of the @tabledata
I think what you mean is that you want to sort [all the rows of] the
file, on the third field of each line/row.
foreach my $row (do {
open my ($data), "<", $file or die "Can't open $file: $!";
sort { $a->[1] cmp $b->[1] }
map { chomp; [(split /\s*¶\s*/)[1..5,7]] }
<DATA>;
} ) {
my @del = @$row;
print join("¶", @del), "\n";
}
--
Klein bottle for rent - inquire within.
------------------------------
Date: 11 Nov 2001 22:11:55 -0800
From: gdbackus@yahoo.com (Greg Backus)
Subject: Re: sorting hashes == headaches
Message-Id: <33a7d0f5.0111112211.278732ea@posting.google.com>
My apologies and my thanks.
Greg
------------------------------
Date: Sun, 11 Nov 2001 23:42:37 GMT
From: Sudhir Krishnan <sudhir@newmail.net>
Subject: sorting qestion
Message-Id: <3BEF0DF1.6010309@newmail.net>
Hi Perl Gurus,
I have an array that contains CGI like strings like:
NAME1=VALUE1&NAME2=VALUE2&NAME3=VALUE3 ....
I want to write a function that will take a particular name
and sort the array based on the values of the names.
So if NAME2 is passed to the function then the array will be sorted
based on the VALUE2 entries in the array.
Can anybody tell me if I can use the sort function in perl
- I've seen things like 'sort keys' in perl but don't know how
to use it.
I'd be glad if I don't have to use bubble sort etc.!
Trying to find a 'perlish' solution for this!
thanks!
Sudhir
------------------------------
Date: Mon, 12 Nov 2001 01:25:34 +0100
From: "Tassilo v. Parseval" <Tassilo.Parseval@post.rwth-aachen.de>
Subject: Re: sorting qestion
Message-Id: <9sn4tu$ddd$01$1@news.t-online.com>
On Sun, 11 Nov 2001 23:42:37 GMT, Sudhir Krishnan wrote:
> Hi Perl Gurus,
>
> I have an array that contains CGI like strings like:
>
> NAME1=VALUE1&NAME2=VALUE2&NAME3=VALUE3 ....
>
> I want to write a function that will take a particular name
> and sort the array based on the values of the names.
>
> So if NAME2 is passed to the function then the array will be sorted
> based on the VALUE2 entries in the array.
>
> Can anybody tell me if I can use the sort function in perl
> - I've seen things like 'sort keys' in perl but don't know how
> to use it.
Yes, you can use the sort function, a little clumsily though: [untested]
sub mysort {
my $field = shift;
return
sort { ($a =~ /$field=(.+)&/)[0] cmp ($b =~ /$field=(.+)&/)[0] } @a;
}
This assumes that $field will not contain any chracters with a special
meaning in regular expressions. If this could be the case, you'd have to
say ...\Q$field\E... to escape those.
It'd be easier to split the array into an array holding references to a
hash and do the sort on that.
For that see the docs on the sort function and
perldoc -q 'sort a hash'
Tassilo
--
Two brothers, Mort and Bill, like to sail. While Bill has a great
deal of experience, he certainly isn't the rigger Mort is.
------------------------------
Date: 11 Nov 2001 23:49:19 GMT
From: eclipsephil@aol.comnospam (Phil)
Subject: timeout of system(sudo prog) using AlarmCall messes up terminal
Message-Id: <20011111184919.28783.00002402@mb-bk.aol.com>
Hi guys,gals
I've got a problem with timing out of sudo. In the example below I have not
authorised my user to run sudo on program x with no password as in 'sudo
/root/x'. This causes the prompt to be displayed and a password expected.
This is not what I want so if I am not setup to run this command I have chosen
to timeout the timed_sudo function. The problem is that when I time out and
then exit the program later it messess up my terminal. By that I mean that if
I press return then I just get the prompt on the same line as before pressing
the return and everything that I type can not be seen but will work. Ie if I
type in ls i do not see the 'ls' on the screen but do see the output of ls.
I am using perl 5.6.0 on mandrake linux in the bash shell in the standard kde
termainl emulator window. Below is an example of my code.
Thanks in advance :
#!/usr/bin/perl -w
use strict;
use Sys::AlarmCall;
my $timeout_alarm = 'TIMEOUT';
my $result;
sub timed_sudo {
system("sudo /root/x");
print "sudo says $?\n";
return 1;
}
$result = alarm_call(7,'timed_sudo');
if ($result eq $timeout_alarm) {
print("Timed out setting up sudo\n");
exit -99;
}
....
more perl here
Live the Journey!
For each destination is but a doorway to another!
------------------------------
Date: Mon, 12 Nov 2001 08:00:53 GMT
From: "Geoff" <geoff@REMOVETHISgeoffball.net>
Subject: Re: Unencoding
Message-Id: <VkLH7.44554$5e2.7525576@news1.telusplanet.net>
"Geoff" <geoff@REMOVETHISgeoffball.net> wrote in message
news:HbLH7.44470$5e2.7520305@news1.telusplanet.net...
> "Geoff" <geoff@REMOVETHISgeoffball.net> wrote in message
> news:n6LH7.44432$5e2.7516665@news1.telusplanet.net...
> > I saw this done before, but can't recall where:
> >
> > Turning all encoded characters in the URL (when submitted in a form)
into
> > their respective unencoded characters.
> >
> > For example:
> >
> > %2F becomes \
> > %3A becomes :
> > etc...
> >
> > It fixes all encoded characters.
> >
> > I'm quite sure I remember seeing tr///, hex(), and the letter 'c' all
used
> > in the algorithm. I appreciate any and all help.
> >
> > Geoff
>
> I just found this on CPAN:
>
> $code =~ s/([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
>
> Is that going to work for all hex codes?
>
> Geoff
Does not work!!
All I get as output is a whole bunch of %'s, which are occasionally followed
by a character (usually letters).
I guess this wasn't what I saw before.
Geoff
------------------------------
Date: Mon, 12 Nov 2001 08:01:49 GMT
From: "Geoff" <geoff@REMOVETHISgeoffball.net>
Subject: Re: Unencoding
Message-Id: <NlLH7.44565$5e2.7525997@news1.telusplanet.net>
"Geoff" <geoff@REMOVETHISgeoffball.net> wrote in message
news:HbLH7.44470$5e2.7520305@news1.telusplanet.net...
> "Geoff" <geoff@REMOVETHISgeoffball.net> wrote in message
> news:n6LH7.44432$5e2.7516665@news1.telusplanet.net...
> > I saw this done before, but can't recall where:
> >
> > Turning all encoded characters in the URL (when submitted in a form)
into
> > their respective unencoded characters.
> >
> > For example:
> >
> > %2F becomes \
> > %3A becomes :
> > etc...
> >
> > It fixes all encoded characters.
> >
> > I'm quite sure I remember seeing tr///, hex(), and the letter 'c' all
used
> > in the algorithm. I appreciate any and all help.
> >
> > Geoff
>
> I just found this on CPAN:
>
> $code =~ s/([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
>
> Is that going to work for all hex codes?
>
> Geoff
Does not work!!
All I get as output is a whole bunch of %'s, which are occasionally followed
by a character (usually letters).
I guess this wasn't what I saw before.
Geoff
------------------------------
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 2113
***************************************