[23417] in Perl-Users-Digest
Perl-Users Digest, Issue: 5635 Volume: 10
daemon@ATHENA.MIT.EDU (Perl-Users Digest)
Wed Oct 8 18:06:09 2003
Date: Wed, 8 Oct 2003 15:05:11 -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 Wed, 8 Oct 2003 Volume: 10 Number: 5635
Today's topics:
Re: //= operator alternative (Roy Johnson)
Re: converting file to excel problem (John McNamara)
File::Copy Adds a ? (Sylvie Stone)
Re: File::Copy Adds a ? (Malcolm Dew-Jones)
Re: File::Copy Adds a ? <xx087@freenet.carleton.ca>
Re: File::Copy Adds a ? <twhu@lucent.com>
Forking in Window enviroment (Herman Chan)
How to get locally configured IP addresses <ama@PW.CA>
I'm a newbie: need to script "init S", then continue ru <tkafer@hotmail.com>
Re: I'm a newbie: need to script "init S", then continu <pinyaj@rpi.edu>
Re: I'm a newbie: need to script "init S", then continu <ddunham@redwood.taos.com>
Re: I'm a newbie: need to script "init S", then continu <tkafer@hotmail.com>
Re: mod_perl, OO and Globals (James Willmore)
Newbie "undefined value" <nadine@mail.sdsu.edu>
Re: Newbie "undefined value" <glex_nospam@qwest.net>
Re: Newbie "undefined value" (Malcolm Dew-Jones)
Re: Newbie needs some help <krahnj@acm.org>
Re: parse boolean logic <pkent77tea@yahoo.com.tea>
Re: pattern matching <nospam@peng.nl>
Re: pattern matching (Malcolm Dew-Jones)
Re: Problem With DBI - fetchrow_array (James Willmore)
Re: Problem With DBI - fetchrow_array <linux@fol.it>
Re: Problem With DBI - fetchrow_array <kkeller-usenet@wombat.san-francisco.ca.us>
Digest Administrivia (Last modified: 6 Apr 01) (Perl-Users-Digest Admin)
----------------------------------------------------------------------
Date: 8 Oct 2003 08:53:42 -0700
From: rjohnson@shell.com (Roy Johnson)
Subject: Re: //= operator alternative
Message-Id: <3ee08638.0310080753.5ebd5b72@posting.google.com>
rgarciasuarez@free.fr (Rafael Garcia-Suarez) wrote in message news:<slrnbo7h1g.p81.rgarciasuarez@rafael.serd.lyon.hexaflux.loc>...
> well, the problem with contexts is that you're going to face
> awkward propagation problems like this one :
> if (defined(foo()) { ... }
> sub foo { $a or $b }
It's lexical, so there's no propagation problem. You're in normal
perl-truth-context unless you're lexically enclosed in another. foo
evaluates $a and $b in its own context, and returns whatever it
normally returns. The defined() interprets that as true, unless it is
undef. That is exactly how that code would work today. If $a is
normal-perl-false, $b is returned, and is evaluated in defined()
context.
More of how I see it:
In this context, variables are checked for definedness first, and if
defined, then return whatever their value is to the expression. That
is to say, they are not autovivified until assigned to, or passed to
subroutines. Details on that may get sticky. I am not a Perl
technician.
defined() itself will return appropriate truth values for whatever
context it is in. That means you don't want to do:
$v = defined( a() || b() || c());
unless you want a boolean result for the whole expression, but
defined($v = a() || b() || c());
if you want $v to get the first defined value. Compare that with
defaulting for undefined $v:
defined($v ||= a() || b() || c());
<And in a different followup>:
> // and //= will be present in perl 5.10.
So I have heard. Where do I look to find how they will work? The
reason I consider it the wrong solution is that, according to an old
document,
if ($a // $b)
doesn't mean "if either is defined". To get that, you have to do ($a
// $b // 0), which is distinctly kludgy. What we really want is a way
to provide a different truth context, hence:
if (defined($a || $b))
It reads beautifully to me.
The drawbacks I have thought of are pretty minor. It is possible,
since exists() and defined() both technically take expressions, that
some weirdly-written code would change behavior. The best example I
could think of:
# Find the first false value and tell me whether it is defined
defined( $a && $b && $c && $d )
If block notation were used, it would be new syntax, and that has some
appeal, considering the special nature of the beast. It doesn't behave
like a function, after all.
defined { $v = $a || $b || $c };
One advantage of // is that you can switch context easily:
# Defined or true or defined or true
$v = $a // $b || $c // $d;
The defined() context would buy you nothing here. I don't see that as
a major issue.
The original syntax I proposed:
defined($v) ||= $a;
could be syntatic sugar for
defined($v ||= $a);
but that raises the question of what to do when you have more on the
right than a simple value:
defined($v) ||= $a || $b;
Is that
defined($v ||= $a || $b);
or
defined($v) || ($v = $a || $b);
?
The latter strikes me as correct.
Thanks for your comments.
------------------------------
Date: 8 Oct 2003 14:45:03 -0700
From: jmcnamara@cpan.org (John McNamara)
Subject: Re: converting file to excel problem
Message-Id: <8cceb2da.0310081345.47357fc3@posting.google.com>
"Shawn" wrote ...
> We are using the below script to convert a file into excel format. The
> problem is that my file contains ssn in which they can start with zero.
> Well, when it gets converted to excel it drops the leading zero. I need
> that leading zero and am not sure how to modify this script to keep the
> zero.
You can fix this by calling the keep_leading_zeros() method for the
worksheet.
...
my $worksheet = $workbook->add_worksheet();
$worksheet->keep_leading_zeros();
...
See the "keep_leading_zeros" section of the Spreadsheet::WriteExcel
documentation for a full explanation.
John.
--
perl -MCPAN -e 'install jmcnamara & _ x ord $ ;' | tail -1
------------------------------
Date: 8 Oct 2003 09:28:53 -0700
From: sylviestone@canada.com (Sylvie Stone)
Subject: File::Copy Adds a ?
Message-Id: <181a24a8.0310080828.7c71697b@posting.google.com>
Hi group -
Can someone tell me why this command is adding a question mark to the file name:
#!/usr/bin/perl
$month=`/bin/date | awk '{print \$2\$6}'`;
if (blah blah blah) {
copy("total.txt","total.$month");
}
[root]# ls -l total.*
-rw-rw-r-- 1 root root 13 Oct 8 12:31 total.Oct2003?
-rw-rw-rw- 1 nobody nobody 13 Oct 8 07:35 total.txt
[root@alert StandardsAlert]# more total.Oct2003?
1|0|0|0|0|1|1
[root@alert StandardsAlert]# more total.Oct2003
total.Oct2003: No such file or directory
THANK YOU!
Syl.
------------------------------
Date: 8 Oct 2003 10:11:39 -0800
From: yf110@vtn1.victoria.tc.ca (Malcolm Dew-Jones)
Subject: Re: File::Copy Adds a ?
Message-Id: <3f84454b@news.victoria.tc.ca>
Sylvie Stone (sylviestone@canada.com) wrote:
: Hi group -
: Can someone tell me why this command is adding a question mark to the
file name:
The date command may be able to output the format you want without using
awk.
$ date '+%b%Y'
Oct2003
: #!/usr/bin/perl
: $month=`/bin/date | awk '{print \$2\$6}'`;
: if (blah blah blah) {
: copy("total.txt","total.$month");
: }
: [root]# ls -l total.*
: -rw-rw-r-- 1 root root 13 Oct 8 12:31 total.Oct2003?
Perhaps it isn't a `?', I will guess the ? is a place holder to indicate a
control character in the name, such as a new-line from the end of the awk
output.
Try chomp($month)
: [root@alert StandardsAlert]# more total.Oct2003?
: 1|0|0|0|0|1|1
That may work because ? is a wild card, so it matches any character (i.e.
a control character) in the file name, not because the filename has a
literal ? .
------------------------------
Date: 8 Oct 2003 18:04:03 GMT
From: Glenn Jackman <xx087@freenet.carleton.ca>
Subject: Re: File::Copy Adds a ?
Message-Id: <slrnbo8kdk.jb8.xx087@smeagol.ncf.ca>
Malcolm Dew-Jones <yf110@vtn1.victoria.tc.ca> wrote:
> Sylvie Stone (sylviestone@canada.com) wrote:
>
> The date command may be able to output the format you want without using
> awk.
>
> $ date '+%b%Y'
> Oct2003
Or don't use date at all:
use POSIX qw(strftime);
$month = strftime "%b%Y", localtime;
> : #!/usr/bin/perl
> : $month=`/bin/date | awk '{print \$2\$6}'`;
[...]
> Perhaps it isn't a `?', I will guess the ? is a place holder to indicate a
> control character in the name, such as a new-line from the end of the awk
> output.
Indeed:
$month=`/bin/date | awk '{print \$2\$6}'`;
$len = length $month;
print "'$month' is $len characters long\n";
--
Glenn Jackman
NCF Sysadmin
glennj@ncf.ca
------------------------------
Date: Wed, 8 Oct 2003 15:08:55 -0400
From: "Tulan W. Hu" <twhu@lucent.com>
Subject: Re: File::Copy Adds a ?
Message-Id: <bm1nec$1du@netnews.proxy.lucent.com>
"Sylvie Stone" <sylviestone@canada.com> wrote in message ...
> Hi group -
>
> Can someone tell me why this command is adding a question mark to the file
name:
>
> #!/usr/bin/perl
> $month=`/bin/date | awk '{print \$2\$6}'`;
**** chomp($month); # maybe the ? is a newline.
>
> if (blah blah blah) {
> copy("total.txt","total.$month");
> }
>
>
>
> [root]# ls -l total.*
> -rw-rw-r-- 1 root root 13 Oct 8 12:31 total.Oct2003?
> -rw-rw-rw- 1 nobody nobody 13 Oct 8 07:35 total.txt
> [root@alert StandardsAlert]# more total.Oct2003?
> 1|0|0|0|0|1|1
> [root@alert StandardsAlert]# more total.Oct2003
> total.Oct2003: No such file or directory
>
>
> THANK YOU!
>
> Syl.
------------------------------
Date: 8 Oct 2003 14:19:29 -0700
From: c24chan@yahoo.ca (Herman Chan)
Subject: Forking in Window enviroment
Message-Id: <55eb5435.0310081319.3a1395a0@posting.google.com>
Hi:
I have the following script
==========================================
#!D:/Perl/bin/Perl.exe -w
use strict;
use CGI ":standard";
$| = 1;
my $MYFILE = "D:\\Apache\\logs\\mgmtwrkstn\\lucky.txt";
if (param("monitor")) {
&monitor();
} else {
if (fork) { # only need to fork for IE
print redirect(-uri => url() . "?monitor=yes",
-nph=>1);
} else {
&do_stuff();
}
sub monitor
{
my $html = &draw_page();
if (defined $html) {
print header(-refresh=>1, -nph=>1), $html;
} else {
print header(-nph=>1), &goodbye();
}
}
sub goodbye
{
return start_html(-title=>"Goodbye!") . h1("Goodbye!") .
end_html();
}
sub get_number
{
open NUMBER, "<$MYFILE" or return undef;
my $number = @glo;
close NUMBER;
return $number;
}
sub draw_page
{
my $number = &get_number();
return (defined $number) ? start_html(-title=>"Your Lucky
Number") . p("Your lucky number is $number.") . end_html() : undef;
}
sub do_stuff
{
for my $i (1 .. 10)
{
open NUMBER2, ">$MYFILE";
print NUMBER2 $i;
close NUMBER2;
sleep 1;
}
unlink $MYFILE;
}
=========================================================
What this script essentially do is that it forks a child process to
write 1 to 10 on some file, while writing it, the parent process will
refresh the page every second to read the content of that file. This
script is orginally from
http://hypernews.ngdc.noaa.gov/HyperNews/get/webscience/2/6/1.html?nogifs
It works under Unix environment with apache. However, when I run this
script in W2K and apache 1.3.x. It doesn't work. It seems like that
the child process is locking the files its writing to and the parent
process can't go into it. Therefore, the parent process doesn't
refresh the page until the child process unlink ("delete") the file.
Can anyone help me on this one? I am a newbie on Perl and CGI and I
want to continuosly monitor some background job on a web page.
Thanks
Herman
------------------------------
Date: Wed, 8 Oct 2003 11:52:47 -0400
From: "A. Ma" <ama@PW.CA>
Subject: How to get locally configured IP addresses
Message-Id: <bm1bt3$dhh21@shark.pwgsc.gc.ca>
Does anyone know how to find out what IP addresses are configured locally?
Thanks.
A.Ma
------------------------------
Date: Wed, 08 Oct 2003 15:55:43 GMT
From: "Kafer" <tkafer@hotmail.com>
Subject: I'm a newbie: need to script "init S", then continue running code
Message-Id: <3sWgb.48098$6C4.2893@pd7tw1no>
Hi all,
I am very new to Perl, so please bear with my lack of experience here. I am
in the process of writing a couple of short Perl scripts to handle some
automated backup procedures to be shipped to some of our customer sites. We
are running Solaris 8 / SPARC, and would like our script to change from
runlevel 3 to runlevel S before executing any code, effectively we want to
issue an "init S" (prompting for root password is ok), then execute our
code.
I can do the init S bit via:
exec init => 'S';
... but of course the script effectively dies at that point. Any ideas? I
don't mind reading if someone knows a how-to or good cookbook site.
Thanks in advance.
------------------------------
Date: Wed, 8 Oct 2003 12:15:11 -0400
From: Jeff 'japhy' Pinyan <pinyaj@rpi.edu>
To: Kafer <tkafer@hotmail.com>
Subject: Re: I'm a newbie: need to script "init S", then continue running code
Message-Id: <Pine.SGI.3.96.1031008121349.50790A-100000@vcmr-64.server.rpi.edu>
[posted & mailed]
On Wed, 8 Oct 2003, Kafer wrote:
>I can do the init S bit via:
>
>exec init => 'S';
>
>... but of course the script effectively dies at that point. Any ideas? I
>don't mind reading if someone knows a how-to or good cookbook site.
That's what exec() DOES. It replaces the current process with the one you
give it. It says "stop running me, and run THIS program instead". You
either want to use system(), which runs the program you tell it to and
THEN returns to the Perl program, or a fork-exec combination.
--
Jeff Pinyan RPI Acacia Brother #734 2003 Rush Chairman
"And I vos head of Gestapo for ten | Michael Palin (as Heinrich Bimmler)
years. Ah! Five years! Nein! No! | in: The North Minehead Bye-Election
Oh. Was NOT head of Gestapo AT ALL!" | (Monty Python's Flying Circus)
------------------------------
Date: Wed, 08 Oct 2003 16:42:13 GMT
From: Darren Dunham <ddunham@redwood.taos.com>
Subject: Re: I'm a newbie: need to script "init S", then continue running code
Message-Id: <F7Xgb.8770$9%7.2207@newssvr29.news.prodigy.com>
Kafer <tkafer@hotmail.com> wrote:
> Hi all,
> I am very new to Perl, so please bear with my lack of experience here. I am
> in the process of writing a couple of short Perl scripts to handle some
> automated backup procedures to be shipped to some of our customer sites. We
> are running Solaris 8 / SPARC, and would like our script to change from
> runlevel 3 to runlevel S before executing any code, effectively we want to
> issue an "init S" (prompting for root password is ok), then execute our
> code.
Ouch. I can think of *no* reason you would ever want to do an 'init S'
on Solaris. 'init 1', maybe.
> I can do the init S bit via:
> exec init => 'S';
*boggle*. You know, I suppose that works just fine, but I would never
write it that way. Why have you used the '=>' operator there?
> ... but of course the script effectively dies at that point. Any ideas? I
> don't mind reading if someone knows a how-to or good cookbook site.
I suggest you read the documentation that comes with perl first.
% perldoc -f exec
exec LIST
exec PROGRAM LIST
The "exec" function executes a system command and
never returns-- use "system" instead of "exec" if
you want it to return.
--
Darren Dunham ddunham@taos.com
Unix System Administrator Taos - The SysAdmin Company
Got some Dr Pepper? San Francisco, CA bay area
< This line left intentionally blank to confuse you. >
------------------------------
Date: Wed, 08 Oct 2003 18:35:07 GMT
From: "Kafer" <tkafer@hotmail.com>
Subject: Re: I'm a newbie: need to script "init S", then continue running code
Message-Id: <vNYgb.48631$6C4.24695@pd7tw1no>
We do an init S to settle down the filesystem before doing a backup via
ufsdump. This script is intended to check the stability of a DiskSuite
mirrored array, bring the system down to init S, detach the array, then dump
the secondary slice. From what I've been reading, it looks like exec will
get me through init S, but what about code after init S?
I was toying with the idea of a one-time rc script to pickup in init S where
init 3 left off, but I hate having scripts lying around that may not get
cleaned up properly in the event of a problem, especially when it could
impact a filesystem.
"Darren Dunham" <ddunham@redwood.taos.com> wrote in message
news:F7Xgb.8770$9%7.2207@newssvr29.news.prodigy.com...
> Kafer <tkafer@hotmail.com> wrote:
> > Hi all,
>
> > I am very new to Perl, so please bear with my lack of experience here. I
am
> > in the process of writing a couple of short Perl scripts to handle some
> > automated backup procedures to be shipped to some of our customer sites.
We
> > are running Solaris 8 / SPARC, and would like our script to change from
> > runlevel 3 to runlevel S before executing any code, effectively we want
to
> > issue an "init S" (prompting for root password is ok), then execute our
> > code.
>
> Ouch. I can think of *no* reason you would ever want to do an 'init S'
> on Solaris. 'init 1', maybe.
>
> > I can do the init S bit via:
>
> > exec init => 'S';
>
> *boggle*. You know, I suppose that works just fine, but I would never
> write it that way. Why have you used the '=>' operator there?
>
> > ... but of course the script effectively dies at that point. Any ideas?
I
> > don't mind reading if someone knows a how-to or good cookbook site.
>
> I suggest you read the documentation that comes with perl first.
>
> % perldoc -f exec
> exec LIST
> exec PROGRAM LIST
> The "exec" function executes a system command and
> never returns-- use "system" instead of "exec" if
> you want it to return.
>
> --
> Darren Dunham ddunham@taos.com
> Unix System Administrator Taos - The SysAdmin Company
> Got some Dr Pepper? San Francisco, CA bay area
> < This line left intentionally blank to confuse you. >
------------------------------
Date: 8 Oct 2003 08:06:39 -0700
From: jwillmore@cyberia.com (James Willmore)
Subject: Re: mod_perl, OO and Globals
Message-Id: <e0160815.0310080706.2976d8d1@posting.google.com>
"M2" <m2@nowhere.com> wrote in message news:<v7Ngb.76$_z4.6584@news.optus.net.au>...
> Hi,
> I'm looking for a way to store some common objects (e.g. a database handle)
> in such a way that it may be accessed from anywhere within an OO based
> mod_perl application.
>
> My first attempt used the UNIVERSAL package to stash it but that felt
> clunky, not to mention risky. For my second attempt I made all objects
> inherit from a single object which returned them from a global. Of course
> this has the potential for some dire issues under mod_perl even though
> they're reset on each execution.
>
> Outside of this I cannot seem to find a way to get the data accessible
> without passing it around all over the place which I would dearly like to
> avoid.
>
> Am I missing something?
A couple of suggestions:
1) _Don't_ use UNIVERSAL unless you know what you're doing. It is my
understanding that it makes all objects available to all classes - and
that _may_ not be what you want to do. It can create inheirtance
issues, as well as overwriting methods and attributes. I could be
wrong about this, but (as of today) that's my understanding.
2) read the documentation on OO: perltoot, perlboot, perlbot.
3) As silly as this may sound, try mapping out what you want to do
first. During this exercise, you may find an easier, faster way to do
things. Redundancy can be eliminated and cleaner code could be
written - just by putting pencil to paper.
4) Get familiar with Data::Dumper. It's a great tool to see where
your values are and how they're being handled.
5) You could investigate some of the DBIx modules (yes, x at the end).
Some of them _may_ deal with what you want to do already.
Persistance with DBI is sometimes a pain. These modules may have
addressed this issue for you.
HTH
Jim
------------------------------
Date: Wed, 08 Oct 2003 10:08:36 -0700
From: Nadine <nadine@mail.sdsu.edu>
Subject: Newbie "undefined value"
Message-Id: <3F844494.4070304@mail.sdsu.edu>
Hello,
I get a "cannot use undefined value as symbol ref at line 45." I have
used strict and -w. I am using CARP. From the command line, my syntax
checks out as OK. From that same command line, if I pass in parameters,
then I get the "undefined value." I thought "strict" would catch all
undefined variables. I am using Perl 5 and Apache.
I had a short script that printed to the browser. Now I am changing it
to print to a file and using parts of Stein's guestbook script. Here is
the resulting script.
#!/usr/bin/perl -w
use strict;
use warnings;
use CGI qw(:standard Carp qw(fatalsToBrowser)); # import shortcuts
use Fcntl qw(:flock); # imports LOCK_EX, LOCK_SH, LOCK_NB
my(
$DATAFILE,
$fh, # File Handle
$TIMEOUT,
$path_name,
$path,
$description,
$lock_type,
);
# give path and name of data file
$DATAFILE="Eval.dat";
my $cgi = CGI->new();
my $value = $cgi->param( 'keyword' ) || '';
sub write_datafile {
my $fh = filelock($DATAFILE,1);
unless ($fh) {
print strong('Sorry, an error occurred: unable to open file.'),p();
Delete('action');
print a({-href=>self_url},'Try again');
return undef;
}
}
# List field names in order.
foreach my $item ( qw(orgclass relevance majorReq course) ) {
my $value = $cgi->param( $item ) || 0;
print $fh "$value . |\n";
}
# Generate web page saying thank you
print $cgi->header,
$cgi->start_html('Thank You'),
$cgi->h2('Thank You'),
$cgi->p("Thank you for your feedback."),
$cgi->p("Return to ", a({-href=>'http://www-rohan.sdsu.edu/~ssrllab/'},
"SSRL Lab home page")),
$cgi->hr({-width=>"100%"}),
$cgi->end_html;
unlock($fh);
1;
sub filelock {
my $path = shift;
my $for_writing = shift;
my ($lock_type,$path_name,$description);
$lock_type = LOCK_EX;
$path_name = ">>$path";
$description = 'writing';
}
local($main::msg,$main::oldsig);
my $handler = sub { $main::msg='timed out';
$SIG{ALRM}=$main::oldsig; };
($main::oldsig,$SIG{ALRM}) = ($SIG{ALRM},$handler);
alarm($TIMEOUT);
open ($fh,$path_name) or
warn("Couldn't open $path for $description: $!"), return undef;
# now try to lock it
unless (flock ($fh,$lock_type)) {
warn("Couldn't get lock for $description (" . ($main::msg ||
"$!") . ")");
alarm(0);
close $fh;
return undef;
}
alarm(0);
return $fh;
sub unlock {
my $fh = shift;
flock($fh,LOCK_UN);
close $fh;
}
------------------------------
Date: Wed, 08 Oct 2003 13:55:22 -0500
From: "J. Gleixner" <glex_nospam@qwest.net>
Subject: Re: Newbie "undefined value"
Message-Id: <Q1Zgb.118$JG4.31776@news.uswest.net>
Nadine wrote:
> Hello,
>
> I get a "cannot use undefined value as symbol ref at line 45."
It's because this:
> # List field names in order.
> foreach my $item ( qw(orgclass relevance majorReq course) ) {
> my $value = $cgi->param( $item ) || 0;
> print $fh "$value . |\n";
> }
runs before this:
[...]
> open ($fh,$path_name) or
> warn("Couldn't open $path for $description: $!"), return undef;
Meaning $fh is an undefined value, when you try to print to it.
If you group all of your subroutines before or after the "main" part of
your code, it might make seeing this much easer. Also, the first '}' in
your filelock sub is likely not in the right place.
See ya
------------------------------
Date: 8 Oct 2003 14:50:54 -0800
From: yf110@vtn1.victoria.tc.ca (Malcolm Dew-Jones)
Subject: Re: Newbie "undefined value"
Message-Id: <3f8486be@news.victoria.tc.ca>
Nadine (nadine@mail.sdsu.edu) wrote:
: Hello,
: I thought "strict" would catch all
: undefined variables. I am using Perl 5 and Apache.
Yes, it catches all undefined * variables *.
You have an undefined * value *.
The variable name has been defined, but you are trying to use the value
before you have given it a value. Often this indicates an error, but the
error cannot (in general) be found until the program is running.
------------------------------
Date: Wed, 08 Oct 2003 16:40:45 GMT
From: "John W. Krahn" <krahnj@acm.org>
Subject: Re: Newbie needs some help
Message-Id: <3F843E0A.796B5124@acm.org>
"Kenneth D. Johnson" wrote:
>
> Here is what I'm trying to do:
>
> I have file1 that has:
> 100
> 200
> 300
> etc.
>
> I have file2 that has
> XXX XX XXXXXX XXXX XXXX [100] AAA
> XXX XX XXXXXX XXXX XXXX [200] BBB
> XXX XX XXXXXX XXXX XXXX [225] CCC
> XXX XX XXXXXX XXXX XXXX [250] DDD
> XXX XX XXXXXX XXXX XXXX [300] EEE
> etc.
>
> I want to find the lines in file2 that contain the numbers in file1 so I can
> write to a third file the A, B, C, D, E info that follows the numbers in
> file2.
#!/usr/bin/perl
use warnings;
use strict;
open my $fh, '<', 'file1' or die "Cannot open file1: $!";
my %find = map { $_ => 1 } do { local $/; <$fh> =~ /\d+/g };
close $fh;
open $fh, '<', 'file2' or die "Cannot open file2: $!";
open my $out, '>', 'file3' or die "Cannot open file3: $!";
while ( <$fh> ) {
if ( / \[ ( \d+ ) ] \s* ( .+ ) /x ) {
print $out "$2\n" if exists $find{ $1 };
}
}
__END__
John
--
use Perl;
program
fulfillment
------------------------------
Date: Wed, 08 Oct 2003 19:55:10 +0100
From: pkent <pkent77tea@yahoo.com.tea>
Subject: Re: parse boolean logic
Message-Id: <pkent77tea-B78571.19551008102003@pth-usenet-02.plus.net>
In article <blup92$o8i$1@news.rz.uni-karlsruhe.de>,
Steffen Müller <sv99oya02@sneakemail.com> wrote:
> Thomas Reat wrote:
> > I have a perl script that must take some boolean logic as input.
> > Something like:
> >
> > ((a || b) & !c) || d || (e && f)
> >
> > Is there any module out there that can help me parse this? And
> > evaluate it as well?
...
> As Sam pointed out earlier, Parse::RecDescent can easily parse such
> expressions. You can find a working example grammar for more involved
> *arithmetic* expressions in the Math::Symbolic::Parser module that is
...
Also, I've found Yapp really good.
http://search.cpan.org/~fdesar/Parse-Yapp-1.05/lib/Parse/Yapp.pm
It was pretty simple to implement arbitrary arithmetic and logical
expressions. To implement just the boolean logic as you have above would
be even easier. In my implementation I used the parser to create a tree
of nodes, of arbitrary depth, and then an evaluation routine walked over
that tree, recursively, deciding its truth (because all you need to get
as a result is a true or false value).
P
--
pkent 77 at yahoo dot, er... what's the last bit, oh yes, com
Remove the tea to reply
------------------------------
Date: Wed, 8 Oct 2003 22:42:50 +0100
From: "Lex" <nospam@peng.nl>
Subject: Re: pattern matching
Message-Id: <LC%gb.580$CT2.57812@news-reader.eresmas.com>
"Bob Walton" <invalid-email@rochester.rr.com> wrote in message
news:3F837912.5060402@rochester.rr.com...
> If you are running this as a CGI script, run it for debugging purposes
> at the command prompt and *use the Perl debugger*. With it you can step
> through your program and observe the values of variables as you go. In
> the excerpt above, for example, you will note that $rec{Text} (why are
> you using a hash to hold just one scalar, anyway??) never gets set to
> anything because the "$word" foreach loop loops over words in
> $rec{Text}, but $rec{Text} starts out empty, so there are never any
> words to start with (if you would pay attention to advice and use
> strict; and use warnings; you would have known that right away). Thus,
> that foreach body is never executed, so $rec{Text} never gets any
> content. Proper indentation of the loops would help understanding of
> the code, too.
>
> You appear to be just trying random things rather than taking a
> systematic approach to your programming problem. You should sit back
> and develop an overview of what you want to do, and then outline the
> small steps needed to accomplish that. Then tackle each of those steps,
> using the debugger to assure that each statement is accomplishing its
> purpose and that you actually have the data you expect in each variable.
> When you get to the end of that, you will have working code.
>
Hi Bob,
you're right obviously but I think I should explain a bit here. It's not
that I don't want to learn, the opposite. But what I've got is a webserver
somewhere and a client. And 2 perl books. And the internet obviously.
I know I can install perl on my windows machine, but I reckon for my scripts
to run (at the end they have to work on a unix-like machine) with all the
path info and stuff it's not worth testing them first on my machine and than
upload and see that stuff doesn't work as it isn't a windows webserver...
To be honest: I lack the time to properly investigate this. Everybody
working with perl seems to talk about command prompt, perl debugger etc...
well it's no option for me (yet) (and to be honest, I don't want/need to use
perl from my command prompt neither). I know you're right when you say what
I need is a systematic approach, but as for now, I still know far too little
to just do it all myself. I need looking at code, trying to see what it does
and once I understand it I can pick it up myself. Most people don't learn
that way I guess, they're better off with a book. I'm crap with books. Good
to have, to search for something when I don't understand what's going on
somewhere. What I'd wish for is more time, more time to learn perl properly,
but as for now, with this site having to be finished the 19th of october...
:)
I'll go back and reread the messages and try to see if I can work it out.
I know my excuses are pretty lame ones, but I guess that's just my situation
right now and I can't change it within a few hours.
Anyway, I really am thankful for the insights you've shown.
Have fun,
Lex
------------------------------
Date: 8 Oct 2003 15:01:18 -0800
From: yf110@vtn1.victoria.tc.ca (Malcolm Dew-Jones)
Subject: Re: pattern matching
Message-Id: <3f84892e@news.victoria.tc.ca>
Lex (nospam@peng.nl) wrote:
: I know I can install perl on my windows machine, but I reckon for my scripts
: to run (at the end they have to work on a unix-like machine) with all the
: path info and stuff it's not worth testing them first on my machine
You're wrong.
: To be honest: I lack the time to properly investigate this.
Sometimes the shortest way there is the long way round.
------------------------------
Date: 8 Oct 2003 08:15:53 -0700
From: jwillmore@cyberia.com (James Willmore)
Subject: Re: Problem With DBI - fetchrow_array
Message-Id: <e0160815.0310080715.7a3a7a11@posting.google.com>
"Pisinho" <linux@fol.it> wrote in message news:<bm0atv$2qc$1@newsreader.mailgate.org>...
> I have thi script, but when I invoke this sub query i have the error:
>
> DBD::mysql::st fetchrow_array failed:fetch() without execute() at
> database.pl line 16, <FILE> line 42
>
>
> sub init_db {
> my $dsn =
> "DBI:$database_driver:database=$database_name;host=$database_host;port=$data
> base_port";
> $db = DBI->connect($dsn,$database_user,$database_password) or return(0);
> }
>
> sub query {
> my $query = shift;
> $handle = $db->prepare($query) or return(0);
> $handle->execute;
> @row = $handle->fetchrow_array; # LINE 16
> if ($handle->rows < 1) {
> @row = ("");
> }
> $handle->finish;
> return @row;
> }
>
>
>
> Where is the problem?
>
> Thanks in advance
$handle->execute or die "Can't execute SQL statement: $DBI::errstr\n";
-or-
$db = DBI->connect(
$dsn,$database_user,
$database_password,
{
PrintError=>0,
RaiseError=>1
}
);
Then you can ditch the various 'return's.
Read the DBI documentation for other error handling methods.
HTH
Jim
------------------------------
Date: Wed, 8 Oct 2003 19:47:57 +0200
From: "Pisinho" <linux@fol.it>
Subject: Re: Problem With DBI - fetchrow_array
Message-Id: <bm1ijb$49n$1@newsreader.mailgate.org>
"James Willmore" <jwillmore@cyberia.com> ha scritto nel messaggio
news:e0160815.0310080715.7a3a7a11@posting.google.com...
> "Pisinho" <linux@fol.it> wrote in message
news:<bm0atv$2qc$1@newsreader.mailgate.org>...
> > I have thi script, but when I invoke this sub query i have the error:
> >
> > DBD::mysql::st fetchrow_array failed:fetch() without execute() at
> > database.pl line 16, <FILE> line 42
> >
With execute() or return 0; I have this error:
DBI::HASH(0x....)
What is?
------------------------------
Date: Wed, 8 Oct 2003 14:56:02 -0700
From: Keith Keller <kkeller-usenet@wombat.san-francisco.ca.us>
Subject: Re: Problem With DBI - fetchrow_array
Message-Id: <i512mb.98g.ln@goaway.wombat.san-francisco.ca.us>
-----BEGIN xxx SIGNED MESSAGE-----
Hash: SHA1
NotDashEscaped: You need GnuPG to verify this message
On 2003-10-08, Pisinho <linux@fol.it> wrote:
>
> With execute() or return 0; I have this error:
>
> DBI::HASH(0x....)
Did you even read James' message where he suggested you could drop all
the 'return 0' stuff? Or his suggestion to read the DBI documentation
for error handling techniques? perldoc DBI for more information.
--keith
--
kkeller-usenet@wombat.san-francisco.ca.us
(try just my userid to email me)
AOLSFAQ=http://wombat.san-francisco.ca.us/cgi-bin/fom
-----BEGIN xxx SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org
iEYEARECAAYFAj+Eh/EACgkQhVcNCxZ5ID8/PwCeNNLTLHX49uE8StNbXE7UQJ7z
5n4An0zmFrf6ev2G7yDS2+Ix2UKMPRze
=h9ga
-----END PGP SIGNATURE-----
------------------------------
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 5635
***************************************