[25793] in Perl-Users-Digest
Perl-Users Digest, Issue: 8032 Volume: 10
daemon@ATHENA.MIT.EDU (Perl-Users Digest)
Sat Apr 30 09:05:31 2005
Date: Sat, 30 Apr 2005 06:05:07 -0700 (PDT)
From: Perl-Users Digest <Perl-Users-Request@ruby.OCE.ORST.EDU>
To: Perl-Users@ruby.OCE.ORST.EDU (Perl-Users Digest)
Perl-Users Digest Sat, 30 Apr 2005 Volume: 10 Number: 8032
Today's topics:
Re: Can this be rewritten better? <tim@vegeta.ath.cx>
Re: Can this be rewritten better? <joe@inwap.com>
Re: Can this be rewritten better? <hackeras@gmail.com>
Re: Looking for Perl Grammar <joe@inwap.com>
Re: multiples ifs <nobull@mail.com>
Re: Perfecting index.pl some more! <hackeras@gmail.com>
Re: Perfecting index.pl some more! <hackeras@gmail.com>
Re: Perfecting index.pl some more! <tadmc@augustmail.com>
Re: Perfecting index.pl some more! <hackeras@gmail.com>
Re: Perfecting index.pl some more! <nobull@mail.com>
Re: Perl windows to linux conversion <joe@inwap.com>
Reading AND writing Excel spreadsheets <colin@pinkmeat.murorum.demon.co.uk>
Re: using LWP to get a very large file <joe@inwap.com>
Digest Administrivia (Last modified: 6 Apr 01) (Perl-Users-Digest Admin)
----------------------------------------------------------------------
Date: Sat, 30 Apr 2005 09:24:51 GMT
From: Tim Hammerquist <tim@vegeta.ath.cx>
Subject: Re: Can this be rewritten better?
Message-Id: <slrnd76jfr.6bc.tim@vegeta.saiyix>
Nikos <hackeras@gmail.com> wrote:
> Tim Hammerquist wrote:
[ snip ]
> > Yes, there's probably a better way to write it. And for a standard
> > fee, many people here would be happy to show you.
>
> Help a newbie man, i cant afford paying....iam trying and laerning by
> asking and finding better ways of writing the code. please.
I'm living proof that you don't have to pay anyone to become a proficient
and effective Perl programmer. It does, however, take a lot of time,
practice, study, and *patience*.
(It's worth noting, however, that even my students, whom I start reading
the standard perldocs on Day 1 of class, are similarly resistant to
RTFM. This needs to be corrected.)
It seems that you're not learning by having us post our tweaks and
optimisations to your code. When we do, you turn right around and ask
us *why* this improves the code. The answer to both latter and former
questions are already freely available in the standard perl
documentation.
Please RTFM. I would hate to be one of the hundreds of people who've
contributed to that vast collection of documentation, only to have
people eschew it in favor of usenet hand-holding. It's there for
good reason; you are part of that reason.
HTH,
Tim Hammerquist
--
Don't anthropomorphise computers. They don't like it.
-- The Register <http://www.theregister.co.uk/content/54/35775.html>
------------------------------
Date: Sat, 30 Apr 2005 03:49:17 -0700
From: Joe Smith <joe@inwap.com>
Subject: Re: Can this be rewritten better?
Message-Id: <6didnRom044u_-7fRVn-1Q@comcast.com>
Henry Law wrote:
>>if( param('select') and param('select') !~ /\.\./ )
>
> I don't know what this is doing but it looks odd to me. I can't
> imagine what the two calls to "param" are returning which when anded
> together could ever look like ".."
They're not anded together. To perform an AND operation on two
integers require using & not && or 'and'. The quoted line translates
to "if param('select') is true (not undef, not '', not 0, not '0')
and the value does not contain two consecutive periods ...".
It probably makes more sense to write it as
if (defined param('select') and param('select') ~= /\.\./) { ... }
-Joe
------------------------------
Date: Sat, 30 Apr 2005 14:18:50 +0300
From: Nikos <hackeras@gmail.com>
Subject: Re: Can this be rewritten better?
Message-Id: <d4vpin$k36$1@nic.grnet.gr>
Joe Smith wrote:
> Henry Law wrote:
>
>>> if( param('select') and param('select') !~ /\.\./ )
>>
>>
>> I don't know what this is doing but it looks odd to me. I can't
>> imagine what the two calls to "param" are returning which when anded
>> together could ever look like ".."
>
>
> They're not anded together. To perform an AND operation on two
> integers require using & not && or 'and'. The quoted line translates
> to "if param('select') is true (not undef, not '', not 0, not '0')
> and the value does not contain two consecutive periods ...".
>
> It probably makes more sense to write it as
> if (defined param('select') and param('select') ~= /\.\./) { ... }
>
> -Joe
I wrote it like this to avoid getting hackers pass cgi parameters to
open files from the adress bar like:
http://www.nikolas.tk/cgi-bin/index.pl?select='../../somepath/somefile') :-)
--
I knew UNIX before it was spelled L I N U X
and
I knew INTERNET before it was spelled W W W
------------------------------
Date: Sat, 30 Apr 2005 03:35:28 -0700
From: Joe Smith <joe@inwap.com>
Subject: Re: Looking for Perl Grammar
Message-Id: <UpmdncXBu9Drwu7fRVn-hQ@comcast.com>
Khamis Abuelkomboz wrote:
> I'm writing a Perl parser and I'm looking for a pure perl grammar.
You won't find it.
My favorite example is this:
#!/usr/bin/perl -l
print time / 2 ; #/; die 'This die() is not executed';
print cos / 2 ; #/; warn 'But this warn() is!';
To resolve the ambiguity of / as numerator/denominator versus m//
requires knowledge of which functions require arguments and which
do not. And if the program has 'use Module;', to determine which
user-defined functions take arguments and which do not requires
actually parsing the Module. You can't do that with pure grammar.
-Joe
------------------------------
Date: Sat, 30 Apr 2005 13:15:02 +0100
From: Brian McCauley <nobull@mail.com>
Subject: Re: multiples ifs
Message-Id: <d4vss6$k8s$1@slavica.ukpost.com>
Scott Bryce wrote:
> Nikos wrote:
>
>> I think there must me a smarter way of writing this.
>
>
> I think it is fine. I would probably do something very similar if I
> wrote it.
Yes, I largely agree with Scott. But I'd change the line
exit 0 if ($i!=0);
To the more ideomatic
exit 0 if $error_found;
(Condister the "read it aloud" test).
I'd also make $error_found a counter using ++ rather than a flag using
=1. It's not necessary and it's actually slightly slower but I find it
more idomatic.
Also since you (Nikos) do the same thing four times to four variables
($name,$pray,$remark,$email) you may want to consider makeing those a
hash. I general if you find you are doing very similar things to a
series of descrete scalars you probably really wanted an agregate.
But rewriting the chain of unless() statements as a loop would probably
only pay off in the short term until you got above four. Of course in
the longer term getting into the habit of always abstracting out anthing
you do _three_ times is good and I see that you (Nikos) sense that.
Does it matter the order in which the tips appear? If not you can put
them in a hash and loop over it. (But only if the fields are in a hash
too).
On a non-Perl issue I suspect the <span> HTML tag would be more
appropriate than the deprocated <font> one. Actually you appear to have
misunderstood what <p> means in HTML. You are confusing it with <br>. It
is illegal (an hense undefined what would happen) to put a <p> inside a
<font> or <span>.
Probably all in all you want a <div>.
my %tips = (
name => 'Name tip',
pray => 'Pray tip',
remark => 'Remark tip',
email => 'Email tips',
);
my $error_found;
for ( keys %tips ) {
unless ( $field{$_} ) {
print div( {class=>'tip'}, $tips{$_});
$error_found++;
}
}
exit 0 if $error_found;
------------------------------
Date: Sat, 30 Apr 2005 10:58:52 +0300
From: Nikos <hackeras@gmail.com>
Subject: Re: Perfecting index.pl some more!
Message-Id: <d4vdrr$au9$1@nic.grnet.gr>
Tassilo v. Parseval wrote:
[snip suggestions to make the code better]
Thanks a lot Tassilo! :-)
The code is much better now with your suggestions:
I dont know what to do with the long lines you said...
You said i dont have to use subs sicne this is nto a big script
and actually iam not repeating any functions more than once.
Well, ok, i dont know if it can gets any shorten than this or
if i can put tha javascript out in a seperate file but still pass the
$data variable.
Also maybe thre is a better wau to create the $data variable instead of
constant concatenations as i have it.
#!/usr/bin/perl
use strict;
use warnings;
use CGI::Carp qw(fatalsToBrowser);
use CGI qw(:standard);
use DBD::mysql;
use POSIX qw(strftime);
print header( -charset=>'iso-8859-7' );
print start_html( -style=>'/data/css/style.css', -title=>'Øõ÷ùöåëÞ
ÐíåõìáôéêÜ Êåßìåíá!', -background=>'/data/images/night.gif' );
my ($sth, $row);
my $date = strftime( "%d %b, %H:%M", localtime );
my $host = $ENV{'REMOTE_HOST'} or $ENV{'REMOTE_ADDR'};
$host = "Íßêïò" if ( ($host eq "dell") or ($host eq "localhost") or
($host =~ /vivodi.gr/) );
my $dbh = ($ENV{'SERVER_NAME'} ne 'nikolas.50free.net')
? DBI->connect('DBI:mysql:nikos_db', 'root', '****')
: DBI->connect('DBI:mysql:nikos_db:50free.net', 'nikos_db', '****')
or {RaiseError=>1};
#*******************************************************************************
my @files = <../data/text/*.txt>;
my @display_files = map( /([^\/]+)\.txt/, @files );
print start_form(-action=>'index.pl');
print p( {-align=>'center'}, font( {class=>'tip'}, 'ÄéÜëåîå Ýíá
áðü ôá êåßìåíá ãéá íá äéáâÜóåéò => ' ),
popup_menu( -name=>'select',
-values=>\@display_files ),
submit('ÅðéëïãÞ'));
print end_form(), br();
my %sql = (
get_counter => "SELECT counter FROM visitorlog",
get_host => "SELECT host FROM visitorlog WHERE host=?",
update_visitor => "UPDATE visitorlog SET counter+=1 WHERE host=?",
update_passage => "UPDATE visitorlog SET passage=? WHERE host=?",
insert_host => "INSERT INTO visitorlog (host, date, passage,
counter) VALUES (?, ?, ?, ?)"
);
my ($data, $counter);
my $passage = param('select') || "Áñ÷éêÞ Óåëßäá!";
if (param('select') and param('select') !~ '..')
{
open(FILE, "<../data/text/$passage.txt") or die $!;
local $/;
$data = <FILE>;
close(FILE);
$sth = $dbh->prepare( $sql{update_passage} );
$sth->execute($passage, $host);
}
else
{
my $sth = $dbh->prepare( $sql{get_host} );
$sth->execute($host);
if ($sth->rows)
{
$sth = $dbh->prepare( $sql{update_visitor} );
$sth->execute($host);
$sth = $dbh->prepare( $sql{get_host} );
$sth->execute($host);
$row = $sth->fetchrow_hashref;
$data = "Êáëþò Þëèåò " .$host. "! ×áßñïìáé ðïõ âñßóêåò ôçí
óåëßäá åíäéáöÝñïõóá!\n" .
"Ôåëåõôáßá öïñÜ Þñèåò åäþ ùò " .$row->{host}. " óôéò "
.$row->{date}. " !!\n" .
"ÓýíïëéêÝò Þñèåò åäþ " .$row->{counter}. " öïñÝò !!\n" .
"Ôåëåõôáßá åßäåò ôï êåßìåíï { " .$row->{passage}. " }\n" .
"Ðïéü êåßìåíï èá ìåëåôÞóåòé áõôÞí ôçí öïñÜ !?";
}
else
{
if ($host ne "Íßêïò")
{
$data = "ÃåéÜ óïõ " .$host. "!\n" .
"¸ñ÷åóáé ãéá 1ç öïñÜ åäþ !!\n" .
"Åëðßæù íá âñåßò ôá êåßìåíá åíäéáöÝñïíôá :-)";
$sth = $dbh->prepare( $sql{insert_host} );
$sth->execute($host, $date, $passage, $counter);
}
else
{
$data = "ÃåéÜ óïõ Íéêüëá, ôé ÷áìðÜñéá?! ¼ëá äåîéÜ íá óïõ
ðÜíå ðÜíôá! ;-)";
}
}
}
$data =~ s/\n/\\n/g;
$data =~ s/"/\\"/g;
$data =~ tr/\cM//d;
#*******************************************************************************
print <<ENDOFHTML;
<html><head><title></title>
<script type='text/javascript'>
var textToShow = "$data";
var tm;
var pos = 0;
var counter = 0;
function init()
{ tm = setInterval("type()", 45) }
function type()
{
if (textToShow.length != pos)
{
d = document.getElementById("DivText");
c = textToShow.charAt(pos++);
if (c.charCodeAt(0) != 10)
d.appendChild(document.createTextNode(c));
else
d.appendChild(document.createElement("br"));
counter++;
if (counter >= 1800 && (c.charCodeAt(0) == 10 || c == "."))
{
d.appendChild(document.createElement("br"));
d.appendChild(document.createTextNode("Press any key..."));
counter = 0;
clearInterval(tm);
document.body.onkeypress = function () {
document.getElementById("DivText").innerHTML = '';
tm = setInterval("type()", 50);
document.body.onkeypress = null; };
}
}
else
clearInterval(tm);
}
</script>
<body onload=init()>
<center>
<div id="DivText" align="Left" style="
background-image: url(../data/images/kenzo.jpg);
border: Ridge Orange 5px;
width: 850px;
height: 500px;
color: LightSkyBlue;
font-family: Times;
font-size: 18px;">
</div
ENDOFHTML
#*******************************************************************************
print br() x 3;
print start_form(-action=>'show.pl');
print table( {class=>'user_form'},
Tr( td( 'Ðþò óå ëÝíå áäåëöå?'
), td( textfield( 'name' ))),
Tr( td( 'ÐïéÜ åßíáé ç ãíþìç óïõ ãéá ôçí åõ÷ïýëá
»Êýñéå Éçóïý ×ñéóôÝ, ÅëÝçóïí Ìå« ?'
), td( textarea( -name=>'pray', -rows=>4, -columns=>25 ))),
Tr( td( 'ÐåñéÝãñáøå ìáò ìéá ðñïóùðéêÞ óïõ
ðíåõìáôéêÞ åìðåéñßá áðü êÜðïéïí ãÝñïíôá ðñïò
þöåëïò ôùí õðïëïßðùí áäåëöþí ( áí öõóéêÜ Ý÷åéò
:-)' ), td( textarea( -name=>'remark', -rows=>6, -columns=>25 ))),
Tr( td( 'Ðïéü åßíáé ôï email óïõ?'
), td( textfield( 'email' ))),
Tr( td( submit( 'ÅìöÜíéóç üëùí ôùí áðüøåùí'
)), td( submit( 'ÁðïóôïëÞ' ))),
);
print end_form();
print br() x 2;
open(FILE, "<../data/text/tips") or die $!;
my @tips = <FILE>;
close(FILE);
@tips = grep { !/^\s*$/ } @tips;
my $tip = $tips[ rand @tips ];
print table( {class=>'info'}, Tr( td( {class=>'tip'}, $tip ))), br();
$sth = $dbh->prepare( $sql{update_counter} ) if ($host ne "Íßêïò");
$sth->execute;
$sth = $dbh->prepare( $sql{get_counter} );
$sth->execute;
while ($row = $sth->fetchrow_hashref)
{
$counter += $row->{counter};
}
print table( {class=>'info'},
Tr( td( {class=>'host'}, $host )),
Tr( td( {class=>'date'}, $date )),
Tr( td( {class=>'counter'}, $counter ))
);
print br(), a( {href=>'games.pl'},
img{src=>'../data/images/games.gif'} );
print p( {-align=>'right'}, a( {href=>'show.pl?name=showlog'}, font(
{-size=>2, -color=>'Lime'}, b( 'Last Update: 30/4/2005' ))));
------------------------------
Date: Sat, 30 Apr 2005 11:15:58 +0300
From: Nikos <hackeras@gmail.com>
Subject: Re: Perfecting index.pl some more!
Message-Id: <d4vert$bn2$1@nic.grnet.gr>
Tassilo v. Parseval wrote:
Also i didnt quite understand what are you tryign to say here!
Can you please clarify it to em some more?
As you want shorter code, here's one way:
s/\n/\\n/g,
s/"/\\"/g ,
tr/\cM//d ,
for $data;
------------------------------
Date: Sat, 30 Apr 2005 05:49:23 -0500
From: Tad McClellan <tadmc@augustmail.com>
Subject: Re: Perfecting index.pl some more!
Message-Id: <slrnd76olj.jat.tadmc@magna.augustmail.com>
Nikos <hackeras@gmail.com> wrote:
> I dont know what to do with the long lines you said...
Errr, make them shorter, what else?
> print start_html( -style=>'/data/css/style.css', -title=>'
> !', -background=>'/data/images/night.gif' );
print start_html( -style=>'/data/css/style.css',
-title=>' !',
-background=>'/data/images/night.gif' );
> print p( {-align=>'center'}, font( {class=>'tip'}, '
> => ' ),
> popup_menu( -name=>'select',
> -values=>\@display_files ),
> submit(''));
print p( {-align=>'center'},
font( {class=>'tip'}, ' '
. ' => ' ),
popup_menu( -name=>'select', -values=>\@display_files ),
submit(''));
Viola! No word-wrapping.
--
Tad McClellan SGML consulting
tadmc@augustmail.com Perl programming
Fort Worth, Texas
------------------------------
Date: Sat, 30 Apr 2005 14:20:42 +0300
From: Nikos <hackeras@gmail.com>
Subject: Re: Perfecting index.pl some more!
Message-Id: <d4vpm7$k36$2@nic.grnet.gr>
Tad McClellan wrote:
> Viola! No word-wrapping.
Cool! ;-)
Smooth Programming Practises!
--
I knew UNIX before it was spelled L I N U X
and
I knew INTERNET before it was spelled W W W
------------------------------
Date: Sat, 30 Apr 2005 13:29:51 +0100
From: Brian McCauley <nobull@mail.com>
Subject: Re: Perfecting index.pl some more!
Message-Id: <d4vtnt$k9n$1@slavica.ukpost.com>
Nikos wrote:
> Also maybe thre is a better wau to create the $data variable instead of
> constant concatenations as i have it.
You mean like where you say:
$data = "Charset I lack " .$host. "! more stuff";
Well it's more ideomatic to use interpolation:
$data = "Charset I lack $host! more stuff";
> $sth = $dbh->prepare( $sql{update_visitor} );
> $sth->execute($host);
Since you don't use that statment handle again after the execute() you
may want to condisder the shorthand form:
$dbh->do( $sql{update_visitor}, {}, $host);
> else
> {
> if ($host ne "Íßêïò")
> {
You may want to consider elsif (that's not a typo, there really is no
'e' in Perl's spelling of 'elseif').
------------------------------
Date: Sat, 30 Apr 2005 03:41:30 -0700
From: Joe Smith <joe@inwap.com>
Subject: Re: Perl windows to linux conversion
Message-Id: <UpmdncTBu9BC_e7fRVn-hQ@comcast.com>
Master wrote:
> i want to convert my windows perl script code to linux.
If your perl script was properly written, and does not use
any Windows-specific modules, simply converting from
Windows line endings ("\r\n") to Unix line endings ("\n")
and adjusting the shebang line should be sufficient.
-Joe
------------------------------
Date: Sat, 30 Apr 2005 09:05:05 +0100
From: Colin Walls <colin@pinkmeat.murorum.demon.co.uk>
Subject: Reading AND writing Excel spreadsheets
Message-Id: <d4ve73$h68$1$8302bc10@news.demon.co.uk>
I am happy creating spreadsheets with Spreadsheet::WriteExcel and reading
them using Spreadsheet::ParseExcel.
However, I have been asked to write data to an already existing spreadsheet.
Is this possible using a mixture of these two modules? If so, how does one
do it?
--
Colin Walls
Removed the pink meat to mail me
------------------------------
Date: Sat, 30 Apr 2005 04:11:52 -0700
From: Joe Smith <joe@inwap.com>
Subject: Re: using LWP to get a very large file
Message-Id: <FbOdncsjgY2f9e7fRVn-vQ@comcast.com>
A. Sinan Unur wrote:
> I found out too late that the Cygwin version of wget that was on my
> machine at the time could not handle file sizes larger than 2GB. OTOH,
> using LWP::Simple, a Perl one liner downloaded the whole DVD image with no
> problem. Of course, the progress indicator was not there, but such is
> life.
Yep, I had to give up on wget for that very reason.
If the server hosting the large file is an FTP server, then you can get
some sense of progress, as shown in http://www.inwap.com/tivo/from-tivo
-Joe
------------------------------
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.
NOTE: due to the current flood of worm email banging on ruby, the smtp
server on ruby has been shut off until further notice.
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 8032
***************************************