[25159] in Perl-Users-Digest

home help back first fref pref prev next nref lref last post

Perl-Users Digest, Issue: 7408 Volume: 10

daemon@ATHENA.MIT.EDU (Perl-Users Digest)
Tue Nov 16 06:05:41 2004

Date: Tue, 16 Nov 2004 03:05:06 -0800 (PST)
From: Perl-Users Digest <Perl-Users-Request@ruby.OCE.ORST.EDU>
To: Perl-Users@ruby.OCE.ORST.EDU (Perl-Users Digest)

Perl-Users Digest           Tue, 16 Nov 2004     Volume: 10 Number: 7408

Today's topics:
        Advice needed: threads and queues <swartz@inbox.ru>
        Cookies (Tuba Chuck)
    Re: Cookies <tadmc@augustmail.com>
        Emacs modules for Perl programming (Jari Aalto+mail.perl)
        FAQ 4.50: How do I select a random element from an arra <comdog@panix.com>
        FAQ 9.19: How do I return the user's mail address? <comdog@panix.com>
    Re: FAQ 9.9: How do I automate an HTML form submission? <ebohlman@omsdev.com>
        hi,something about thread in perl <x.t.hua@163.com>
        i want this printed on my nightie secretadmirer@secret.com 
    Re: i want this printed on my nightie <nospam@bigpond.com>
    Re: i want this printed on my nightie <matthew.garrish@sympatico.ca>
    Re: i want this printed on my nightie <nospam@bigpond.com>
    Re: Is PHP still slower than Perl? <dformosa@zeta.org.au>
        Minimizing chance of race conditions (Duke of Hazard)
    Re: Minimizing chance of race conditions <jurgenex@hotmail.com>
    Re: Minimizing chance of race conditions <tassilo.von.parseval@rwth-aachen.de>
    Re: Need RegExp <someone@example.com>
    Re: OPEN command <soxos@libero.it>
    Re: OPEN command (Michele Dondi)
        Digest Administrivia (Last modified: 6 Apr 01) (Perl-Users-Digest Admin)

----------------------------------------------------------------------

Date: Tue, 16 Nov 2004 04:23:04 -0600
From: "Swartz" <swartz@inbox.ru>
Subject: Advice needed: threads and queues
Message-Id: <10pjkum6r1vf009@corp.supernews.com>

Hi all.

I'm fairly new to Perl (less then 6 months of programming experience).

I'm trying to write a small threaded "proof of concept" application.
Basic ideas:
 - there is a number of songs users can listen to,
 - each song can only be accessed by one user at a time
 - each user can only listen to one song at a time,

This is the part I'm working on right now.

--------------------- <begin code> ---------------------
#!/usr/bin/perl

use threads;
use threads::shared;
use Thread::Queue;

print "MAIN THREAD: start!\n";

# Hash of songs
%song = ("1" => "Song 1",
         "2" => "Song 2",
         "3" => "Song 3",
         "4" => "Song 4",
         "5" => "Song 5",
         "6" => "Song 6",
         "7" => "Song 7",
         "8" => "Song 8");


# 'share' the individual values of %song hash
foreach $key (keys %song) {
        share ($song{$key});
}


# spin off 10 threads (a.k.a users)
for ($i = 0; $i < 10 ; $i++) {
        new threads \&login;
}

# Loop through all the threads and 'join' them (credit: perlthrtut)
foreach $thr (threads->list) {
        # Don't join the main thread or ourselves
        if ($thr->tid && !threads::equal($thr, threads->self)) {
            $thr->join;
        }
}

print "MAIN THREAD: done!\n";


#######################################################
sub login {
        my $ThreadID = threads->self->tid;
        print "Thread ${ThreadID}: started\n";
        # random song from 1 to 8 for testing
        request_song(int rand (8)+1);
}

#######################################################
sub request_song {
        my $song_num = shift @_;
        my $ThreadID = threads->self->tid;
        print "Thread ${ThreadID}: requesting song $song_num...\n";
        lock $song{$song_num};
        listen_to_song($song_num);
        print "Thread ${ThreadID}: finished playing song $song_num\n";
}

#######################################################
sub listen_to_song {
        my $song_num = shift @_;
        my $song_time = int rand (9)+1;
        $ThreadID = threads->self->tid;
        print "Thread ${ThreadID}: listening to song $song_num for
$song_time seconds\n";
        # pretending to listen to music
        sleep $song_time;
}

----------------------------- <end code> ---------------------------------


What I am trying to do is add a queue for users (or threads for now) who are
trying to request a song that is currently being played ('lock'-ed).
Consequently I wish to display current queue contents at any given time
(although this is not very important right now).
I've ran into a number of questions,
1. How to determine if a particular song is already in use by another thread
and place a request into the queue? Attempting to do something like:
eval (block ($song{$n}))
to check for existing data blocks results in the thread waiting for data to
be unlocked (as expected as I now found out).
2. How to incorporate the queue into my code? One problem being is that I
don't need to enqueue every request for songs, as there will be requests
that can go through now without having to wait for other requests in the
queue ahead of them.

I thought of spinning off a separate thread and a queue for each song,
however it seems like an even more complicated approach.

Any help is appreciated...

Thanks in advance!

PS. I'm using Perl v5.8.5, with threads of course ;)





------------------------------

Date: 15 Nov 2004 19:29:19 -0800
From: charles.teague@gmail.com (Tuba Chuck)
Subject: Cookies
Message-Id: <7234602.0411151929.48b93ee3@posting.google.com>

Im trying to make a script that will login to my Pitas blog and then
post an entry.  I seem to be having problems with the cookies.  The
script is:
#!/usr/bin/perl
use HTTP::Request::Common qw(POST);
use LWP::UserAgent;
use HTTP::Cookies;

#Get needed info
print 'Login: ';
$uname = <STDIN>;
print 'Password: ';
$pass = <STDIN>;
print 'Date: ';
$date = <STDIN>;
print 'Time: ';
$time = <STDIN>;
print 'Title: ';
$pagename = <STDIN>;
print 'Entry: ';
$entry = <STDIN>;

$cookie_jar = HTTP::Cookies->new();

$login = LWP::UserAgent->new();
my $reql = POST 'http://www.pitas.com/cgi-bin/login.phtml', [
'username' => $uname, 'password' => $pass, 'remember_me' => 'no' ];
$responsel = $login->request($reql);

$addent = LWP::UserAgent->new();
my $requ = POST 'http://www.pitas.com/cgi-bin/update.phtml', [ 'date'
=> $date, 'time' => $time, 'url' => '#', 'pagename' => $pagename,
'entry' => $entry ];
$cookie_jar->add_cookie_header($requ);
$cookie_jar->extract_cookies($responsel);
$addent->request($requ);

exit;


------------------------------

Date: Mon, 15 Nov 2004 22:37:38 -0600
From: Tad McClellan <tadmc@augustmail.com>
Subject: Re: Cookies
Message-Id: <slrncpj10i.2ip.tadmc@magna.augustmail.com>

Tuba Chuck <charles.teague@gmail.com> wrote:

> I seem to be having problems with the cookies.
> script is:

> #!/usr/bin/perl

   use warnings;
   use strict;

Ask for all the help you can get!


> $cookie_jar = HTTP::Cookies->new();
> 
> $login = LWP::UserAgent->new();


   $login->cookie_jar($cookie_jar);

You never associated that cookie jar with the user agent.


> my $reql = POST 'http://www.pitas.com/cgi-bin/login.phtml', [
> 'username' => $uname, 'password' => $pass, 'remember_me' => 'no' ];
> $responsel = $login->request($reql);

> $addent = LWP::UserAgent->new();


Why do you need another UserAgent?

Just reuse $login.


-- 
    Tad McClellan                          SGML consulting
    tadmc@augustmail.com                   Perl programming
    Fort Worth, Texas


------------------------------

Date: 16 Nov 2004 05:28:39 GMT
From: <jari.aalto <AT> poboxes.com> (Jari Aalto+mail.perl)
Subject: Emacs modules for Perl programming
Message-Id: <perl-faq/emacs-lisp-modules_1100582874@rtfm.mit.edu>

Archive-name: perl-faq/emacs-lisp-modules
Posting-Frequency: 2 times a month
URL: http://tiny-tools.sourceforge.net/
Maintainer: Jari Aalto A T poboxes com

Announcement: "What Emacs lisp modules can help with programming Perl"

    Preface

        Emacs is your friend if you have to do anything comcerning software
        development: It offers plug-in modules, written in Emacs lisp
        (elisp) language, that makes all your programmings wishes come
        true. Please introduce yourself to Emacs and your programming era
        will get a new light.

    Where to find Emacs/XEmacs

        o   Unix:
            http://www.gnu.org/software/emacs/emacs.html
            http://www.xemacs.org/

        o   Unix Windows port (for Unix die-hards):
            install http://www.cygwin.com/  which includes native Emacs 21.x.
            and XEmacs port

        o   Pure Native Windows port
            http://www.gnu.org/software/emacs/windows/ntemacs.html
            ftp://ftp.xemacs.org/pub/xemacs/windows/setup.exe

        o   More Emacs resources at
            http://tiny-tools.sourceforge.net/  => Emacs resource page

Emacs Perl Modules

    Cperl -- Perl programming mode

        http://www.cpan.org/modules/by-authors/id/ILYAZ/cperl-mode/
        http://math.berkeley.edu/~ilya/software/emacs/
        by Ilya Zakharevich

        CPerl is major mode for editing perl files. Forget the default
        `perl-mode' that comes with Emacs, this is much better. Comes
        standard in newest Emacs.

    TinyPerl -- Perl related utilities

        http://tiny-tools.sourceforge.net/

        If you ever wonder how to deal with Perl POD pages or how to find
        documentation from all perl manpages, this package is for you.
        Couple of keystrokes and all the documentaion is in your hands.

        o   Instant function help: See documentation of `shift', `pop'...
        o   Show Perl manual pages in *pod* buffer
        o   Grep through all Perl manpages (.pod)
        o   Follow POD references e.g. [perlre] to next pod with RETURN
        o   Coloured pod pages with `font-lock'
        o   Separate `tiperl-pod-view-mode' for jumping topics and pages
            forward and backward in *pod* buffer.

        o   Update `$VERSION' variable with YYYY.MMDD on save.
        o   Load source code into Emacs, like Devel::DProf.pm
        o   Prepare script (version numbering) and Upload it to PAUSE
        o   Generate autoload STUBS (Devel::SelfStubber) for you
            Perl Module (.pm)

    TinyIgrep -- Perl Code browsing and easy grepping

        [TinyIgrep is included in Tiny Tools Kit]

        To grep from all installed Perl modules, define database to
        TinyIgrep. There is example file emacs-rc-tinyigrep.el that shows
        how to set up dattabases for Perl5, Perl4 whatever you have
        installed

        TinyIgrep calls Igrep.el to to do the search, You can adjust
        recursive grep options, set search case sensitivity, add user grep
        options etc.

        You can find latest `igrep.el' module at
        <http://groups.google.com/groups?group=gnu.emacs.sources> The
        maintainer is Jefin Rodgers <kevinr <AT> ihs.com>.

    TinyCompile -- To Browse grep results in Emacs *compile* buffer

        TinyCompile is a minor mode for *compile* buffer from where
        you can collapse unwanted lines or shorten file URLs:

            /asd/asd/asd/asd/ads/as/da/sd/as/as/asd/file1:NNN: MATCHED TEXT
            /asd/asd/asd/asd/ads/as/da/sd/as/as/asd/file2:NNN: MATCHED TEXT

            -->

            cd /asd/asd/asd/asd/ads/as/da/sd/as/as/asd/
            file1:NNN: MATCHED TEXT
            file1:NNN: MATCHED TEXT

End



------------------------------

Date: Tue, 16 Nov 2004 05:03:00 +0000 (UTC)
From: PerlFAQ Server <comdog@panix.com>
Subject: FAQ 4.50: How do I select a random element from an array?
Message-Id: <cnc1m4$dce$1@reader1.panix.com>

This message is one of several periodic postings to comp.lang.perl.misc
intended to make it easier for perl programmers to find answers to
common questions. The core of this message represents an excerpt
from the documentation provided with Perl.

--------------------------------------------------------------------

4.50: How do I select a random element from an array?

    Use the rand() function (see "rand" in perlfunc):

        $index   = rand @array;
        $element = $array[$index];

    Or, simply: my $element = $array[ rand @array ];



--------------------------------------------------------------------

Documents such as this have been called "Answers to Frequently
Asked Questions" or FAQ for short.  They represent an important
part of the Usenet tradition.  They serve to reduce the volume of
redundant traffic on a news group by providing quality answers to
questions that keep coming up.

If you are some how irritated by seeing these postings you are free
to ignore them or add the sender to your killfile.  If you find
errors or other problems with these postings please send corrections
or comments to the posting email address or to the maintainers as
directed in the perlfaq manual page.

Note that the FAQ text posted by this server may have been modified
from that distributed in the stable Perl release.  It may have been
edited to reflect the additions, changes and corrections provided
by respondents, reviewers, and critics to previous postings of
these FAQ. Complete text of these FAQ are available on request.

The perlfaq manual page contains the following copyright notice.

  AUTHOR AND COPYRIGHT

    Copyright (c) 1997-2002 Tom Christiansen and Nathan
    Torkington, and other contributors as noted. All rights 
    reserved.

This posting is provided in the hope that it will be useful but
does not represent a commitment or contract of any kind on the part
of the contributers, authors or their agents.


------------------------------

Date: Tue, 16 Nov 2004 11:03:02 +0000 (UTC)
From: PerlFAQ Server <comdog@panix.com>
Subject: FAQ 9.19: How do I return the user's mail address?
Message-Id: <cncmp6$ik3$1@reader1.panix.com>

This message is one of several periodic postings to comp.lang.perl.misc
intended to make it easier for perl programmers to find answers to
common questions. The core of this message represents an excerpt
from the documentation provided with Perl.

--------------------------------------------------------------------

9.19: How do I return the user's mail address?

    On systems that support getpwuid, the $< variable, and the Sys::Hostname
    module (which is part of the standard perl distribution), you can
    probably try using something like this:

        use Sys::Hostname;
        $address = sprintf('%s@%s', scalar getpwuid($<), hostname);

    Company policies on mail address can mean that this generates addresses
    that the company's mail system will not accept, so you should ask for
    users' mail addresses when this matters. Furthermore, not all systems on
    which Perl runs are so forthcoming with this information as is Unix.

    The Mail::Util module from CPAN (part of the MailTools package) provides
    a mailaddress() function that tries to guess the mail address of the
    user. It makes a more intelligent guess than the code above, using
    information given when the module was installed, but it could still be
    incorrect. Again, the best way is often just to ask the user.



--------------------------------------------------------------------

Documents such as this have been called "Answers to Frequently
Asked Questions" or FAQ for short.  They represent an important
part of the Usenet tradition.  They serve to reduce the volume of
redundant traffic on a news group by providing quality answers to
questions that keep coming up.

If you are some how irritated by seeing these postings you are free
to ignore them or add the sender to your killfile.  If you find
errors or other problems with these postings please send corrections
or comments to the posting email address or to the maintainers as
directed in the perlfaq manual page.

Note that the FAQ text posted by this server may have been modified
from that distributed in the stable Perl release.  It may have been
edited to reflect the additions, changes and corrections provided
by respondents, reviewers, and critics to previous postings of
these FAQ. Complete text of these FAQ are available on request.

The perlfaq manual page contains the following copyright notice.

  AUTHOR AND COPYRIGHT

    Copyright (c) 1997-2002 Tom Christiansen and Nathan
    Torkington, and other contributors as noted. All rights 
    reserved.

This posting is provided in the hope that it will be useful but
does not represent a commitment or contract of any kind on the part
of the contributers, authors or their agents.


------------------------------

Date: 16 Nov 2004 07:32:19 GMT
From: Eric Bohlman <ebohlman@omsdev.com>
Subject: Re: FAQ 9.9: How do I automate an HTML form submission?
Message-Id: <Xns95A310B70ED97ebohlmanomsdevcom@130.133.1.4>

PerlFAQ Server <comdog@panix.com> wrote in
news:cnbcj8$736$1@reader1.panix.com: 

> 9.9: How do I automate an HTML form submission?
> 
>     If you're submitting values using the GET method, create a URL and
>     encode the form using the "query_form" method:
> 
>         use LWP::Simple;
>         use URI::URL;
> 
>         my $url = url('http://www.perl.com/cgi-bin/cpan_mod');
>         $url->query_form(module => 'DB_File', readme => 1);
>         $content = get($url);
> 
>     If you're using the POST method, create your own user agent and
>     encode the content appropriately.
> 
>         use HTTP::Request::Common qw(POST);
>         use LWP::UserAgent;
> 
>         $ua = LWP::UserAgent->new();
>         my $req = POST 'http://www.perl.com/cgi-bin/cpan_mod',
>                        [ module => 'DB_File', readme => 1 ];
>         $content = $ua->request($req)->as_string;

Might be worth mentioning WWW::Mechanize for use in more complex 
interactions.


------------------------------

Date: Tue, 16 Nov 2004 13:04:44 +0000
From: XiaotingHua <x.t.hua@163.com>
Subject: hi,something about thread in perl
Message-Id: <cnc1rd$2qqq$1@mail.cn99.com>

i 'd like to write threaded perl program in a IBM machine which contain
8 cpu and install AIX 5.1 .

i look at the perlthrtut , and find perl thread is just like the fork in

  unix, which is expensive.

is perl thread in user-mode or kernel mode? AIX 5.1 support kernel
thread, and can automatic put the task to all processers.but user thread
  only can do all work in one processer. and if perl thread is only
running in one processer, it 's senceless for me to do thread program.

any advise? thank you!


------------------------------

Date: Tue, 16 Nov 2004 02:32:05 -0000
From: secretadmirer@secret.com 
Subject: i want this printed on my nightie
Message-Id: <10pipl578mc4hac@news.supernews.com>

#!/usr/bin/perl

join in, open me and split it;



------------------------------

Date: Tue, 16 Nov 2004 13:32:55 +1000
From: Gregory Toomey <nospam@bigpond.com>
Subject: Re: i want this printed on my nightie
Message-Id: <2vtan7F2q2ci7U1@uni-berlin.de>

secretadmirer@secret.com  wrote:

> #!/usr/bin/perl
> 
> join in, open me and split it;

its on sale already:
http://www.thinkgeek.com/tshirts/coder/321a/

gtoomey


------------------------------

Date: Mon, 15 Nov 2004 23:10:40 -0500
From: "Matt Garrish" <matthew.garrish@sympatico.ca>
Subject: Re: i want this printed on my nightie
Message-Id: <35fmd.7668$rc.648608@news20.bellglobal.com>


"Gregory Toomey" <nospam@bigpond.com> wrote in message 
news:2vtan7F2q2ci7U1@uni-berlin.de...
> secretadmirer@secret.com  wrote:
>
>> #!/usr/bin/perl
>>
>> join in, open me and split it;
>
> its on sale already:
> http://www.thinkgeek.com/tshirts/coder/321a/
>

I think this is just an example of slightly on-topic spam...

Matt 




------------------------------

Date: Tue, 16 Nov 2004 19:03:38 +1000
From: Gregory Toomey <nospam@bigpond.com>
Subject: Re: i want this printed on my nightie
Message-Id: <2vtu3dF2mkt7nU1@uni-berlin.de>

Matt Garrish wrote:

> 
> "Gregory Toomey" <nospam@bigpond.com> wrote in message
> news:2vtan7F2q2ci7U1@uni-berlin.de...
>> secretadmirer@secret.com  wrote:
>>
>>> #!/usr/bin/perl
>>>
>>> join in, open me and split it;
>>
>> its on sale already:
>> http://www.thinkgeek.com/tshirts/coder/321a/
>>
> 
> I think this is just an example of slightly on-topic spam...
> 
> Matt

Do you think I owm http://www.ostg.com/ ?

gtoomey


------------------------------

Date: 16 Nov 2004 19:59:52 +1100
From: ? the Platypus {aka David Formosa} <dformosa@zeta.org.au>
Subject: Re: Is PHP still slower than Perl?
Message-Id: <m3zn1i9njr.fsf@dformosa.zeta.org.au>

Simon Stienen <simon.stienen@news.slashlife.de> writes:

[...]

> Please explain the difference between safety and security.

Security is against hostile attackers, safety is against the code
screwing up.  Because of C's nature your forced to use pointers all
over the place, and because C lacks a Garbage Collector its quite easy
to free memory, that you later on attempt to use.  This causes a
sementation fault (or worse), and the code crashes.

So called scriting lanagues and functional lanaguges get past this
limiation by having a garbage collector and systems that mean pointer
equiverlents are safe.

> If you've done this:
> *What* is bad about header files and the preprocessor?

Because the preprocessor works purly as text substitution, because it
isn't realy part of the language it can screw up things up in hideous
ways.  For example header files don't impose any sort of namespaceing
so its quite possable to have name space collisions between diffrent
sets of included libaries.

[...]

> By now, your whole post shouts:
> "I don't have a clue about C, so it *has* to be bad."

I've programed extensivly in C, and I know how bad it is.


-- 
Please excuse my spelling as I suffer from agraphia. See
http://dformosa.zeta.org.au/~dformosa/Spelling.html to find out more.
Free the Memes.


------------------------------

Date: 15 Nov 2004 20:17:39 -0800
From: squash@peoriadesignweb.com (Duke of Hazard)
Subject: Minimizing chance of race conditions
Message-Id: <2d21b838.0411152017.510ff893@posting.google.com>

It is imperative that a section of my code is only executed by only
one user at a time. So I have my program write a lock file when it
reaches that section , then remove the lock file after it completes
that section.

This seemed to work ok, until I knew about race conditions. So I
changed the code to write the lock file twice. First at the beginning
of the script and second when it reaches the critical section of code
that must be executed by only 1 user at a time.

I figure this will significantly lower my probability of a race
condition since two race conditions will need to occur simultaneously
for it to break (which I am fine with, as long as it happens less than
once per 1000 times).

Is that right, or am I missing something?

Thanks!


------------------------------

Date: Tue, 16 Nov 2004 05:05:22 GMT
From: "Jürgen Exner" <jurgenex@hotmail.com>
Subject: Re: Minimizing chance of race conditions
Message-Id: <mUfmd.4730$J55.3162@trnddc06>

Duke of Hazard wrote:
[...]
> I figure this will significantly lower my probability of a race
> condition since two race conditions will need to occur simultaneously
> for it to break (which I am fine with, as long as it happens less than
> once per 1000 times).
>
> Is that right, or am I missing something?

Why don't you use code that does not have a race condition?
"perldoc -q lock"

jue




------------------------------

Date: Tue, 16 Nov 2004 06:14:38 +0100
From: "Tassilo v. Parseval" <tassilo.von.parseval@rwth-aachen.de>
Subject: Re: Minimizing chance of race conditions
Message-Id: <slrncpj35u.po.tassilo.von.parseval@localhost.localdomain>

Also sprach Duke of Hazard:

> It is imperative that a section of my code is only executed by only
> one user at a time. So I have my program write a lock file when it
> reaches that section , then remove the lock file after it completes
> that section.
>
> This seemed to work ok, until I knew about race conditions. So I
> changed the code to write the lock file twice. First at the beginning
> of the script and second when it reaches the critical section of code
> that must be executed by only 1 user at a time.
>
> I figure this will significantly lower my probability of a race
> condition since two race conditions will need to occur simultaneously
> for it to break (which I am fine with, as long as it happens less than
> once per 1000 times).
>
> Is that right, or am I missing something?

It's still wrong. Avoiding race conditions means that the chance of one
occuring is zero. You merely lowered its probability. But if there is
still a chance of a race condition, your code remains broken.

You should only create one lockfile, but do it properly. It has to be an
atomic operation:

    select undef, undef, undef, 0.5
	while ! sysopen LOCK, "file.lock", O_WRONLY|O_EXCL|O_CREAT;

    # once the program reaches this line, it succesfully acquired a
    # lock-file

    ...

    close LOCK;
    unlink "file.lock" or die "Something happened to the lock file: $!";

The above, by the way, is reasonably portable.

There's a number of FAQ entries dealing with locking. See 

    perldoc -q lock

Tassilo
-- 
$_=q#",}])!JAPH!qq(tsuJ[{@"tnirp}3..0}_$;//::niam/s~=)]3[))_$-3(rellac(=_$({
pam{rekcahbus})(rekcah{lrePbus})(lreP{rehtonabus})!JAPH!qq(rehtona{tsuJbus#;
$_=reverse,s+(?<=sub).+q#q!'"qq.\t$&."'!#+sexisexiixesixeseg;y~\n~~dddd;eval


------------------------------

Date: Tue, 16 Nov 2004 10:28:22 GMT
From: "John W. Krahn" <someone@example.com>
Subject: Re: Need RegExp
Message-Id: <aDkmd.104911$VA5.49376@clgrps13>

Indigo5 wrote:
> I need a way of parsing a variable format.  Basically the section starts off
> with a Reference keyword and ends with a Comments keyword.
> 
> Reference:
> 1.  document1
> 2   document2
> Comments:
> 
> I was doing this as follows:
> 
> if (/^Reference/ .. /^Comments/){
> 
>    if (/^[0-9]/){
> 
>       chomp;
> 
>       $_ =~ s/^[0-9].\s+//g;
> 
>       push @references, $_;
>    }
> }
> 
> However, I just received a document where Reference 1 wrapped onto another
> line so that the format looks like this:
> 
> Reference:
> 1.  document 1
>      more of document 1 here
> 2. document 2
> Comments:
> 
> I cannot change the format of the input I receive, so I have to find a way
> to parse this the way I receive it.  Any help would be highly appreciated.


$_ = <FILE> until /^Reference/;

while ( <FILE> ) {
     last if /^Comments/;
     chomp;
     s/^\d+\.\s+// ? push( @references, $_ ) : ( $references[ -1 ] .= $_ );
     }



John
-- 
use Perl;
program
fulfillment


------------------------------

Date: Tue, 16 Nov 2004 08:47:17 GMT
From: Soxos <soxos@libero.it>
Subject: Re: OPEN command
Message-Id: <opshjuo2kefj1z64@homer>

I'm sorry, my question didn't follow the netiquette, but, as I just saw,=
  =

even you "gurus" aren't agree on the form and on the substance of the  =

problem...

I've already spent some hours on my problem, perhaps searching in the  =

wrong places, so I thought you could answer me in a while!
That wasn't right, so I repeat I'm sorry!

I will search on PERLDOC (THIS is a good suggestion, without you have to=
  =

remark that open is not a command!).

Bye!


------------------------------

Date: 16 Nov 2004 02:15:51 -0800
From: bik.mido@gmail.com (Michele Dondi)
Subject: Re: OPEN command
Message-Id: <bdabe82.0411160215.496f54ca@posting.google.com>

Ala Qumsieh <notvalid@email.com> wrote in message news:<_y5md.21515$6q2.798@newssvr14.news.prodigy.com>...

> >>	while(<fileIN>)
> >>		{
> >>		$_ =~ s/\n/ /;
[snip]
> > Also I *guess* that one may want to
> > 
> >   s/\n/ /g;
> >   #      ^
> > 
> > instead. (But I may well be wrong on this!)
> 
> I believe you are :)

Of course I am!! For some reason I thought that $_ could contain
multiple \n's: I posted in a hurry and I didn't even realize that it
was more-bad-codese for "chomp() and append a space". (Now I slap my
forhead!)

> FWIW, I would've done things like this:
> 
> 	chomp;
> 	$content .= " $_";
> 
> But, TMTOWTDI.

Well, we always insist to process line by line, but since the OP won't
discard any, this could probably be one of the cases in which

  chomp (my @lines = <fileIN>);
  $content = "@lines";

or something along the same lines is sensible.


Michele
-- 
{$_=pack'B8'x25,unpack'A8'x32,$a^=sub{pop^pop}->(map substr
(($a||=join'',map--$|x$_,(unpack'w',unpack'u','G^<R<Y]*YB='
 .'KYU;*EVH[.FHF2W+#"\Z*5TI/ER<Z`S(G.DZZ9OX0Z')=~/./g)x2,$_,
256),7,249);s/[^\w,]/ /g;$ \=/^J/?$/:"\r";print,redo}#JAPH,


------------------------------

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 7408
***************************************


home help back first fref pref prev next nref lref last post