[31353] in Perl-Users-Digest
Perl-Users Digest, Issue: 2605 Volume: 11
daemon@ATHENA.MIT.EDU (Perl-Users Digest)
Sun Sep 20 14:09:43 2009
Date: Sun, 20 Sep 2009 11:09: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 Sun, 20 Sep 2009 Volume: 11 Number: 2605
Today's topics:
Re: Am I doing this wrong? Why does this seem so clumsy <pavlovevidence@gmail.com>
Re: Am I doing this wrong? Why does this seem so clumsy <gallium.arsenide@gmail.com>
Re: Am I doing this wrong? Why does this seem so clumsy <skye.shaw@gmail.com>
Am I doing this wrong? Why does this seem so clumsy (ti <schifschaf@gmail.com>
Re: Am I doing this wrong? Why does this seem so clumsy <ben@morrow.me.uk>
Re: appending to a file. <rodbass63@gmail.com>
Re: appending to a file. sln@netherlands.com
Button in WWW::Mechanize <john1949@yahoo.com>
Re: Button in WWW::Mechanize <no@email.com>
FAQ 4.60 How do I sort a hash (optionally by value inst <brian@theperlreview.com>
FAQ 4.73 How do I keep persistent data across program c <brian@theperlreview.com>
FAQ 5.33 How do I dup() a filehandle in Perl? <brian@theperlreview.com>
FAQ 5.37 Why does Perl let me delete read-only files? <brian@theperlreview.com>
FAQ 8.35 How do I close a process's filehandle without <brian@theperlreview.com>
Re: IPC::Open2::open2() -- How to pass strings stdin, s <jerrykrinock@gmail.com>
Re: Newbie: Perl script to Windows and Linux executable <jurgenex@hotmail.com>
Re: Newbie: Perl script to Windows and Linux executable <spamtrap@shermpendley.com>
Re: regex match for same number of opening and closing sln@netherlands.com
Digest Administrivia (Last modified: 6 Apr 01) (Perl-Users-Digest Admin)
----------------------------------------------------------------------
Date: Sat, 19 Sep 2009 19:57:00 -0700 (PDT)
From: Carl Banks <pavlovevidence@gmail.com>
Subject: Re: Am I doing this wrong? Why does this seem so clumsy (time, datetime vs. DateTime)
Message-Id: <1799eec4-b492-4b59-aba1-c11f39cfca5d@s21g2000prm.googlegroups.com>
On Sep 19, 7:22=A0pm, Schif Schaf <schifsc...@gmail.com> wrote:
> The other day I needed to convert a date like "August 2009" into a
> "seconds-since-epoch" value (this would be for the first day of that
> month, at the first second of that day).
>
> In Python, I came up with this:
>
> ~~~~
> #!/usr/bin/env python
>
> import datetime
> import time
>
> time_in_sse =3D time.mktime(
> =A0 =A0 datetime.datetime(2009, 8, 1).timetuple()
> )
>
> print time_in_sse
> ~~~~
>
> I *wanted* to just use time.mktime(), but it wouldn't work unless I
> could specify the *complete* time tuple value (who would have all that
> handy?!).
Was it really that hard to add a few zeros to the tuple for values you
didn't know?
time.mktime((2009, 8, 1, 0, 0, 0, 0, 0, -1))
Carl Banks
------------------------------
Date: Sat, 19 Sep 2009 20:58:56 -0700 (PDT)
From: John Yeung <gallium.arsenide@gmail.com>
Subject: Re: Am I doing this wrong? Why does this seem so clumsy (time, datetime vs. DateTime)
Message-Id: <399c8f0e-e5dd-4530-b25c-e8b80227ef48@z28g2000vbl.googlegroups.com>
On Sep 19, 10:57=A0pm, Carl Banks <pavlovevide...@gmail.com> wrote:
> On Sep 19, 7:22=A0pm, Schif Schaf <schifsc...@gmail.com> wrote:
>
> > I *wanted* to just use time.mktime(), but it wouldn't
> > work unless I could specify the *complete* time tuple
> > value (who would have all that handy?!).
>
> Was it really that hard to add a few zeros to the tuple
> for values you didn't know?
>
> time.mktime((2009, 8, 1, 0, 0, 0, 0, 0, -1))
To be fair, the docs for the time module (I'm looking at the help file
for 2.6.2) are written in such a way that it's not clear you can use
zero for the unknown day of the week or day of the year. The passage
for time.mktime(t) that states "If the input value cannot be
represented as a valid time, either OverflowError or ValueError will
be raised" *might* imply that your tuple is invalid, because
2009-08-01 was not a Monday and 0 is not even in the valid range for
tm_yday. In my opinion, this is a deficiency of the docs.
On the other hand, I think the OP, as well as users of Python in
general, should probably not be so timid. Just try something and see
if it works. Throw zeros in for the unknown values and maybe you'll
get a ValueError (like your cautious, doc-respecting mind is
expecting) or maybe the routine will actually do the appropriate and
convenient thing and trust your year, month, and day. In this case,
the latter is happily true.
For what it's worth, it's true that the time module is not
particularly Pythonic. It's mostly a wrapper for C library functions,
and the docs do imply this near the top. Personally, I think the
wrapper could stand to be less thin and provide friendlier access
while still using the C library, but I doubt it's a big enough pain
point to spur anyone to improve it.
John
------------------------------
Date: Sat, 19 Sep 2009 21:19:31 -0700 (PDT)
From: "Skye Shaw!@#$" <skye.shaw@gmail.com>
Subject: Re: Am I doing this wrong? Why does this seem so clumsy (time, datetime vs. DateTime)
Message-Id: <a28ca752-8cf8-47e7-a4f9-afbc4217b173@m33g2000pri.googlegroups.com>
On Sep 19, 7:22=A0pm, Schif Schaf <schifsc...@gmail.com> wrote:
> The other day I needed to convert a date like "August 2009" into a
> "seconds-since-epoch" value (this would be for the first day of that
> month, at the first second of that day).
You could use Time::Piece:
[sshaw@localhost ~]$ perl -lMTime::Piece -e'$t=3DTime::Piece->strptime
("August 2009","%b %Y"); print $t->epoch'
1249084800
------------------------------
Date: Sat, 19 Sep 2009 19:22:42 -0700 (PDT)
From: Schif Schaf <schifschaf@gmail.com>
Subject: Am I doing this wrong? Why does this seem so clumsy (time, datetime vs. DateTime)
Message-Id: <dded2752-9d9f-4bdc-a9bd-b96c4516f2d1@r36g2000vbn.googlegroups.com>
The other day I needed to convert a date like "August 2009" into a
"seconds-since-epoch" value (this would be for the first day of that
month, at the first second of that day).
In Python, I came up with this:
~~~~
#!/usr/bin/env python
import datetime
import time
time_in_sse = time.mktime(
datetime.datetime(2009, 8, 1).timetuple()
)
print time_in_sse
~~~~
I *wanted* to just use time.mktime(), but it wouldn't work unless I
could specify the *complete* time tuple value (who would have all that
handy?!). I also wanted to then just do datetime.datetime
(...).secs_since_epoch(), but it didn't support a function like that
-- not one I could find anyway.
Note, to arrive at that above solution, I had to spend a fair amount
of time reading the docs on both the time and datetime modules, and
then wondering why the methods I wanted weren't there. Am I missing
something and maybe used the wrong methods/modules here?
Contrast this to Perl, where the solution I came up with in about 5
minutes was:
~~~~
#!/usr/bin/env perl
use DateTime;
my $dt = DateTime->new(year => 2009, month => 8);
print $dt->epoch, "\n";
~~~~
(it only took 5 minutes because the docs for DateTime tell you exactly
what you want to know right at the top on the first page of the docs.)
------------------------------
Date: Sun, 20 Sep 2009 07:02:35 +0100
From: Ben Morrow <ben@morrow.me.uk>
Subject: Re: Am I doing this wrong? Why does this seem so clumsy (time, datetime vs. DateTime)
Message-Id: <r4tgo6-ha81.ln1@osiris.mauzo.dyndns.org>
[This is not a Perl question. F'ups set to c.l.python.]
Quoth Schif Schaf <schifschaf@gmail.com>:
> The other day I needed to convert a date like "August 2009" into a
> "seconds-since-epoch" value (this would be for the first day of that
> month, at the first second of that day).
Note that this is not unique: you need to at least specify a time zone.
Ben
------------------------------
Date: Sat, 19 Sep 2009 05:41:47 -0700 (PDT)
From: Nene <rodbass63@gmail.com>
Subject: Re: appending to a file.
Message-Id: <c94a9ec7-0aca-436f-9601-f831f94d2147@o21g2000vbl.googlegroups.com>
On Aug 31, 4:13=A0pm, mer...@stonehenge.com (Randal L. Schwartz) wrote:
> >>>>> "Nene" =3D=3D Nene =A0<rodbas...@gmail.com> writes:
>
> Nene> Greetings, I want to open an apache file and append a line at the b=
ottom
> Nene> of all theListenentries, not the bottom of the file. For example, I
> Nene> want to append once it finds the lastListenentry in the file. For
> Nene> example, the lastListenentry is 'Listen8150', I want to append
> Nene> 'Listen8151' underneathListen8150. From what I read, I might have t=
o
> Nene> use a module, but I'm trying not install modules. Is it possible?
>
> Nene>Listen80Listen5555Listen443Listen7170Listen8002Listen8005
> Nene>Listen8008Listen8009Listen8010Listen8011Listen8013Listen8022
> Nene>Listen8023Listen8024Listen8045Listen8050Listen8051Listen8102
> Nene>Listen8108Listen8155Listen8110Listen8210Listen8211Listen8263
> Nene>Listen8122Listen8145Listen8346Listen8347Listen8147Listen8148
> Nene>Listen8146Listen8150
>
> Use "in-place-edit" mode:
>
> =A0 =A0 my $line_to_insert =3D "Listen8151\n";
>
> =A0 =A0 {
> =A0 =A0 =A0 local @ARGV =3D "/path/to/your/httpd.conf";
> =A0 =A0 =A0 local $^I =3D ".bak"; # appended to the backup copy
>
> =A0 =A0 =A0 while (<>) {
>
> =A0 =A0 =A0 =A0 if ((/^Listen/..!/^Listen/) =3D~ /e/) { # if we're at the=
end of the Listens
> =A0 =A0 =A0 =A0 =A0 $_ =3D $line_to_insert . $_; # prepend the line to th=
e next line
> =A0 =A0 =A0 =A0 }
> =A0 =A0 =A0 =A0 print; # but print whatever we have
> =A0 =A0 =A0 }
>
> =A0 =A0 }
>
> print "Just another Perl hacker,"; # the original
>
> --
> Randal L. Schwartz - Stonehenge Consulting Services, Inc. - +1 503 777 00=
95
> <mer...@stonehenge.com> <URL:http://www.stonehenge.com/merlyn/>
> Smalltalk/Perl/Unix consulting, Technical writing, Comedy, etc. etc.
> Seehttp://methodsandmessages.vox.com/for Smalltalk and Seaside discussion
Umm, I thought it worked but it's not working, probably because I'm
missing something. I created a new file and it has:
Listen 80
Listen 81
Listen 82
But when I run:
#!/usr/bin/perl -w
use strict;
my $line_to_insert =3D "Listen 8151\n";
{
local @ARGV =3D "/home/control/misc_perl_scripts/httpd.conf";
local $^I =3D ".bak"; # appended to the backup copy
while (<>) {
if ((/^Listen/..!/^Listen/) =3D~ /e/) { # if we're at the end of
the Listens
$_ =3D $line_to_insert . $_; # prepend the line to the next
line
}
print; # but print whatever we have
}
}
__END__
It doesn't print the $line_to_insert, and it doesn't print anything,
the file remains the same? Any clue?
Nene
------------------------------
Date: Sat, 19 Sep 2009 06:08:27 -0700
From: sln@netherlands.com
Subject: Re: appending to a file.
Message-Id: <0sl9b5hhdl7noet1r2519fjjn95emc4gv5@4ax.com>
On Sat, 19 Sep 2009 05:41:47 -0700 (PDT), Nene <rodbass63@gmail.com> wrote:
>On Aug 31, 4:13 pm, mer...@stonehenge.com (Randal L. Schwartz) wrote:
>> >>>>> "Nene" == Nene <rodbas...@gmail.com> writes:
>>
>Umm, I thought it worked but it's not working, probably because I'm
>missing something. I created a new file and it has:
>
>Listen 80
>Listen 81
>Listen 82
>
>But when I run:
>
>#!/usr/bin/perl -w
>use strict;
>
>my $line_to_insert = "Listen 8151\n";
> {
> local @ARGV = "/home/control/misc_perl_scripts/httpd.conf";
> local $^I = ".bak"; # appended to the backup copy
> while (<>) {
> if ((/^Listen/..!/^Listen/) =~ /e/) { # if we're at the end of
^
E
>the Listens
> $_ = $line_to_insert . $_; # prepend the line to the next
>line
> }
> print; # but print whatever we have
> }
> }
>
>
>__END__
>
>It doesn't print the $line_to_insert, and it doesn't print anything,
>the file remains the same? Any clue?
>
>Nene
-sln
------------------------------
Date: Sun, 20 Sep 2009 16:02:14 +0100
From: "John" <john1949@yahoo.com>
Subject: Button in WWW::Mechanize
Message-Id: <h95g5k$frf$1@news.albasani.net>
Just checking there is nothing odd about the button in WWW::Mechanize.
I have <input type='button' name='This One' ... etc>
I am using
$agent->click('This One');
print $agent->$content();
It accepts the button but does move to the next page.
Regards
John
------------------------------
Date: Sun, 20 Sep 2009 16:43:23 +0100
From: Brian Wakem <no@email.com>
Subject: Re: Button in WWW::Mechanize
Message-Id: <7hn0ssF2u95veU1@mid.individual.net>
John wrote:
> Just checking there is nothing odd about the button in WWW::Mechanize.
>
> I have <input type='button' name='This One' ... etc>
>
> I am using
>
> $agent->click('This One');
> print $agent->$content();
>
> It accepts the button but does move to the next page.
>
Since Buttons don't actually submit forms (type='submit' does)there is no
next page. There is probably an 'onclick' in the input field that points
at some javascript, which WWW::Mechanize will ignore.
--
Brian Wakem
------------------------------
Date: Sat, 19 Sep 2009 16:00:02 GMT
From: PerlFAQ Server <brian@theperlreview.com>
Subject: FAQ 4.60 How do I sort a hash (optionally by value instead of key)?
Message-Id: <6e7tm.45570$ec2.15809@newsfe13.iad>
This is an excerpt from the latest version perlfaq4.pod, which
comes with the standard Perl distribution. These postings aim to
reduce the number of repeated questions as well as allow the community
to review and update the answers. The latest version of the complete
perlfaq is at http://faq.perl.org .
--------------------------------------------------------------------
4.60: How do I sort a hash (optionally by value instead of key)?
(contributed by brian d foy)
To sort a hash, start with the keys. In this example, we give the list
of keys to the sort function which then compares them ASCIIbetically
(which might be affected by your locale settings). The output list has
the keys in ASCIIbetical order. Once we have the keys, we can go through
them to create a report which lists the keys in ASCIIbetical order.
my @keys = sort { $a cmp $b } keys %hash;
foreach my $key ( @keys )
{
printf "%-20s %6d\n", $key, $hash{$key};
}
We could get more fancy in the "sort()" block though. Instead of
comparing the keys, we can compute a value with them and use that value
as the comparison.
For instance, to make our report order case-insensitive, we use the "\L"
sequence in a double-quoted string to make everything lowercase. The
"sort()" block then compares the lowercased values to determine in which
order to put the keys.
my @keys = sort { "\L$a" cmp "\L$b" } keys %hash;
Note: if the computation is expensive or the hash has many elements, you
may want to look at the Schwartzian Transform to cache the computation
results.
If we want to sort by the hash value instead, we use the hash key to
look it up. We still get out a list of keys, but this time they are
ordered by their value.
my @keys = sort { $hash{$a} <=> $hash{$b} } keys %hash;
From there we can get more complex. If the hash values are the same, we
can provide a secondary sort on the hash key.
my @keys = sort {
$hash{$a} <=> $hash{$b}
or
"\L$a" cmp "\L$b"
} keys %hash;
--------------------------------------------------------------------
The perlfaq-workers, a group of volunteers, maintain the perlfaq. They
are not necessarily experts in every domain where Perl might show up,
so please include as much information as possible and relevant in any
corrections. The perlfaq-workers also don't have access to every
operating system or platform, so please include relevant details for
corrections to examples that do not work on particular platforms.
Working code is greatly appreciated.
If you'd like to help maintain the perlfaq, see the details in
perlfaq.pod.
------------------------------
Date: Sat, 19 Sep 2009 22:00:06 GMT
From: PerlFAQ Server <brian@theperlreview.com>
Subject: FAQ 4.73 How do I keep persistent data across program calls?
Message-Id: <Gvctm.228108$vp.113897@newsfe12.iad>
This is an excerpt from the latest version perlfaq4.pod, which
comes with the standard Perl distribution. These postings aim to
reduce the number of repeated questions as well as allow the community
to review and update the answers. The latest version of the complete
perlfaq is at http://faq.perl.org .
--------------------------------------------------------------------
4.73: How do I keep persistent data across program calls?
For some specific applications, you can use one of the DBM modules. See
AnyDBM_File. More generically, you should consult the "FreezeThaw" or
"Storable" modules from CPAN. Starting from Perl 5.8 "Storable" is part
of the standard distribution. Here's one example using "Storable"'s
"store" and "retrieve" functions:
use Storable;
store(\%hash, "filename");
# later on...
$href = retrieve("filename"); # by ref
%hash = %{ retrieve("filename") }; # direct to hash
--------------------------------------------------------------------
The perlfaq-workers, a group of volunteers, maintain the perlfaq. They
are not necessarily experts in every domain where Perl might show up,
so please include as much information as possible and relevant in any
corrections. The perlfaq-workers also don't have access to every
operating system or platform, so please include relevant details for
corrections to examples that do not work on particular platforms.
Working code is greatly appreciated.
If you'd like to help maintain the perlfaq, see the details in
perlfaq.pod.
------------------------------
Date: Sun, 20 Sep 2009 10:00:01 GMT
From: PerlFAQ Server <brian@theperlreview.com>
Subject: FAQ 5.33 How do I dup() a filehandle in Perl?
Message-Id: <B2ntm.58091$4t6.43778@newsfe06.iad>
This is an excerpt from the latest version perlfaq5.pod, which
comes with the standard Perl distribution. These postings aim to
reduce the number of repeated questions as well as allow the community
to review and update the answers. The latest version of the complete
perlfaq is at http://faq.perl.org .
--------------------------------------------------------------------
5.33: How do I dup() a filehandle in Perl?
If you check "open" in perlfunc, you'll see that several of the ways to
call open() should do the trick. For example:
open(LOG, ">>/foo/logfile");
open(STDERR, ">&LOG");
Or even with a literal numeric descriptor:
$fd = $ENV{MHCONTEXTFD};
open(MHCONTEXT, "<&=$fd"); # like fdopen(3S)
Note that "<&STDIN" makes a copy, but "<&=STDIN" make an alias. That
means if you close an aliased handle, all aliases become inaccessible.
This is not true with a copied one.
Error checking, as always, has been left as an exercise for the reader.
--------------------------------------------------------------------
The perlfaq-workers, a group of volunteers, maintain the perlfaq. They
are not necessarily experts in every domain where Perl might show up,
so please include as much information as possible and relevant in any
corrections. The perlfaq-workers also don't have access to every
operating system or platform, so please include relevant details for
corrections to examples that do not work on particular platforms.
Working code is greatly appreciated.
If you'd like to help maintain the perlfaq, see the details in
perlfaq.pod.
------------------------------
Date: Sun, 20 Sep 2009 16:00:04 GMT
From: PerlFAQ Server <brian@theperlreview.com>
Subject: FAQ 5.37 Why does Perl let me delete read-only files? Why does "-i" clobber protected files? Isn't this a bug in Perl?
Message-Id: <8kstm.238497$ZN.113755@newsfe23.iad>
This is an excerpt from the latest version perlfaq5.pod, which
comes with the standard Perl distribution. These postings aim to
reduce the number of repeated questions as well as allow the community
to review and update the answers. The latest version of the complete
perlfaq is at http://faq.perl.org .
--------------------------------------------------------------------
5.37: Why does Perl let me delete read-only files? Why does "-i" clobber protected files? Isn't this a bug in Perl?
This is elaborately and painstakingly described in the file-dir-perms
article in the "Far More Than You Ever Wanted To Know" collection in
http://www.cpan.org/misc/olddoc/FMTEYEWTK.tgz .
The executive summary: learn how your filesystem works. The permissions
on a file say what can happen to the data in that file. The permissions
on a directory say what can happen to the list of files in that
directory. If you delete a file, you're removing its name from the
directory (so the operation depends on the permissions of the directory,
not of the file). If you try to write to the file, the permissions of
the file govern whether you're allowed to.
--------------------------------------------------------------------
The perlfaq-workers, a group of volunteers, maintain the perlfaq. They
are not necessarily experts in every domain where Perl might show up,
so please include as much information as possible and relevant in any
corrections. The perlfaq-workers also don't have access to every
operating system or platform, so please include relevant details for
corrections to examples that do not work on particular platforms.
Working code is greatly appreciated.
If you'd like to help maintain the perlfaq, see the details in
perlfaq.pod.
------------------------------
Date: Sun, 20 Sep 2009 04:00:02 GMT
From: PerlFAQ Server <brian@theperlreview.com>
Subject: FAQ 8.35 How do I close a process's filehandle without waiting for it to complete?
Message-Id: <6Nhtm.228131$vp.58967@newsfe12.iad>
This is an excerpt from the latest version perlfaq8.pod, which
comes with the standard Perl distribution. These postings aim to
reduce the number of repeated questions as well as allow the community
to review and update the answers. The latest version of the complete
perlfaq is at http://faq.perl.org .
--------------------------------------------------------------------
8.35: How do I close a process's filehandle without waiting for it to complete?
Assuming your system supports such things, just send an appropriate
signal to the process (see "kill" in perlfunc). It's common to first
send a TERM signal, wait a little bit, and then send a KILL signal to
finish it off.
--------------------------------------------------------------------
The perlfaq-workers, a group of volunteers, maintain the perlfaq. They
are not necessarily experts in every domain where Perl might show up,
so please include as much information as possible and relevant in any
corrections. The perlfaq-workers also don't have access to every
operating system or platform, so please include relevant details for
corrections to examples that do not work on particular platforms.
Working code is greatly appreciated.
If you'd like to help maintain the perlfaq, see the details in
perlfaq.pod.
------------------------------
Date: Sat, 19 Sep 2009 06:30:45 -0700 (PDT)
From: Jerry Krinock <jerrykrinock@gmail.com>
Subject: Re: IPC::Open2::open2() -- How to pass strings stdin, stdout?
Message-Id: <6b430510-4e6a-4795-b033-032db02f10f9@m3g2000pri.googlegroups.com>
Eventually I got into utf8 warnings with my temporary file, so rather
than look up my Perl UTF8 Incantations Cheat Sheet, I waited a few
minutes for CPAN to install IPC::Run and used Charles' one-liner.
Thanks, Charles ... I would not have made it through the IPC::Run
documentation without that!
------------------------------
Date: Sat, 19 Sep 2009 04:39:31 -0700
From: Jürgen Exner <jurgenex@hotmail.com>
Subject: Re: Newbie: Perl script to Windows and Linux executable versions.
Message-Id: <big9b59lc0pi58j5566v9bcip8etrbt2bh@4ax.com>
Harry <simonsharry@gmail.com> wrote:
>[...] I don't want my logic to be leaked to anyone outside my
>development team.
Why didn't you say so in the beginning?
See "perldoc -q hide"
jue
------------------------------
Date: Sat, 19 Sep 2009 11:18:24 -0400
From: Sherm Pendley <spamtrap@shermpendley.com>
Subject: Re: Newbie: Perl script to Windows and Linux executable versions.
Message-Id: <m2bpl7gdz3.fsf@shermpendley.com>
Harry <simonsharry@gmail.com> writes:
> uname='linux x86-7.fedora.phx.redhat.com 2.6.18-128.1.14.el5 #1
Some Linux distros have a separate perl-dev or perl-devel package. Try
looking in your package manager for something like that.
sherm--
------------------------------
Date: Sat, 19 Sep 2009 06:20:22 -0700
From: sln@netherlands.com
Subject: Re: regex match for same number of opening and closing brackets
Message-Id: <g2m9b51b0su1h8bl1sjctkc4c5g42d7go3@4ax.com>
On Fri, 18 Sep 2009 14:06:08 -0700, sln@netherlands.com wrote:
>On Fri, 18 Sep 2009 14:22:05 +0200, Sascha Bendix <sascha.bendix@localroot.de> wrote:
>
>>Hi,
>>
>>I got a little parsing problem right here: I got some strings and want
>>to ensure, that there are as many opening as closing brackets via a
>>regex without specifying the exact number.
>>
>>This regex would be part of a bigger one, so it can't be done in two steps.
>>
>>Can anybody give me a hint how to do this?
>>
Try this modified version. This regex accepts strings
as open and close balanced text. It will still do single
character.
'$x,$y' are the open,close text variables below.
-sln
----------------------------
use strict;
use warnings;
my $debug = 1;
my $string = "ga <a>this<a>{s<a>{ds}</a>g}</a>that-this</a> g <a>dn gd</a> that{fn} asdf </a>ga";
my ($x,$y) =
(
'<a>',
'</a>'
);
my ($xp,$yp) = ($x,$y);
$_ = quotemeta for ($x,$y);
my $rxbal = qr {
(?:
($x (?:(?>(?:(?!$x|$y).)+) | (?1))* $y) # Group 1
| ($x|$y) # Group 2
| .
)+
}xs;
if ($debug)
{
use re 'eval';
$rxbal = qr {
(?:
( # Group 1
$x
(?{ print "\n x => '$xp'",pos(); })
(?:
(?> (?: (?!$x|$y) . )+ ) # no backtracking and not ($x|$y)
|
(?{ print "-",pos(); })
(?1) # Recurse to start of group 1
)*
$y
(?{ print "\n y => '$yp'",pos(); })
)
(?{ print "\n* \$1 => '$^N'",pos(); })
|
($x|$y) # Group 2, $x or $y
(?{ print "\n! \$2 => (____bad____) '$^N'",pos(); })
|
(.) # Group 3, any char
(?{ print "\n \$3 => '$^N'",pos(); })
)+
(?{ print "\n"; })
}xs;
}
print "\nx = '$xp'\ny = '$yp'\n",'-'x20,"\n'$string'\n";
if ($string =~ /$rxbal/)
{
print "\n";
if (defined $2)
{ print "** This is NOT balanced\n" }
elsif (not defined $1)
{ print "** Nothing to balance\n" }
else
{ print "** This is balanced\n" }
}
else
{ print "** The string is empty\n" }
__END__
Output:
x = '<a>'
y = '</a>'
--------------------
'ga <a>this<a>{s<a>{ds}</a>g}</a>that-this</a> g <a>dn gd</a> that{fn} asdf </a>
ga'
$3 => 'g'1
$3 => 'a'2
$3 => ' '3
x => '<a>'6-10
x => '<a>'13-15
x => '<a>'18-22
y => '</a>'26-28
y => '</a>'32-41
y => '</a>'45
* $1 => '<a>this<a>{s<a>{ds}</a>g}</a>that-this</a>'45
$3 => ' '46
$3 => 'g'47
$3 => ' '48
x => '<a>'51-56
y => '</a>'60
* $1 => '<a>dn gd</a>'60
$3 => ' '61
$3 => 't'62
$3 => 'h'63
$3 => 'a'64
$3 => 't'65
$3 => '{'66
$3 => 'f'67
$3 => 'n'68
$3 => '}'69
$3 => ' '70
$3 => 'a'71
$3 => 's'72
$3 => 'd'73
$3 => 'f'74
$3 => ' '75
! $2 => (____bad____) '</a>'79
$3 => 'g'80
$3 => 'a'81
** This is NOT balanced
------------------------------
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:
To submit articles to comp.lang.perl.announce, send your article to
clpa@perl.com.
Back issues are available via anonymous ftp from
ftp://cil-www.oce.orst.edu/pub/perl/old-digests.
#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 V11 Issue 2605
***************************************