[22315] in Perl-Users-Digest

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

Perl-Users Digest, Issue: 4536 Volume: 10

daemon@ATHENA.MIT.EDU (Perl-Users Digest)
Mon Feb 10 18:37:49 2003

Date: Mon, 10 Feb 2003 15:36:32 -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           Mon, 10 Feb 2003     Volume: 10 Number: 4536

Today's topics:
        Modify array elements using foreach ? <someone@somewhere.nl>
    Re: Modify array elements using foreach ? <jkeen@concentric.net>
    Re: Modify array elements using foreach ? <jkeen@concentric.net>
    Re: Modify array elements using foreach ? <someone@somewhere.nl>
    Re: Modify array elements using foreach ? ctcgag@hotmail.com
    Re: Modify array elements using foreach ? <someone@somewhere.nl>
    Re: Modify array elements using foreach ? <tassilo.parseval@post.rwth-aachen.de>
        MySQL DBI <andrew.rich@bigpond.com>
    Re: MySQL DBI <goldbb2@earthlink.net>
    Re: Need a bit of help with LWP <anthonysaffer@NOSPAM.yahoo.com>
    Re: Need a bit of help with LWP <eric.schwartz@hp.com>
    Re: Need a bit of help with LWP (Tad McClellan)
        Need to order alpha numeric codes with Perl/Mysql (J Capenos)
    Re: Need to order alpha numeric codes with Perl/Mysql (Tad McClellan)
    Re: Need to order alpha numeric codes with Perl/Mysql <goldbb2@earthlink.net>
    Re: Need to order alpha numeric codes with Perl/Mysql <abigail@abigail.nl>
    Re: Need to order alpha numeric codes with Perl/Mysql <spamtrap@nowhere.com>
    Re: Need to order alpha numeric codes with Perl/Mysql <tassilo.parseval@post.rwth-aachen.de>
        need to recreate an awk script in Perl (Felini)
    Re: need to recreate an awk script in Perl <jkeen@concentric.net>
    Re: need to recreate an awk script in Perl <steven.smolinski@sympatico.ca>
    Re: need to recreate an awk script in Perl <krahnj@acm.org>
    Re: need to recreate an awk script in Perl <goldbb2@earthlink.net>
    Re: need to recreate an awk script in Perl <krahnj@acm.org>
        Digest Administrivia (Last modified: 6 Apr 01) (Perl-Users-Digest Admin)

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

Date: Sat, 8 Feb 2003 17:09:54 +0100
From: "Stefan" <someone@somewhere.nl>
Subject: Modify array elements using foreach ?
Message-Id: <3e452c55$0$150$e4fe514c@dreader8.news.xs4all.nl>

Hello all,

Something, I didnt notice before, is puzzling me. When stepping through all
elements in an array, changing the current element will automatically update
the array. Even if there is a grep involved (example 1). The same thing but
on an associative-array, does not seem to do that (example 2).

Although Im currently using "Perl v5.6.1 built for i386-freebsd", it seems
perl-version independent.

When checking the description of foreach, I could not find anything which
explains this behaviour. Google didnt help either. Or did I miss something ?
Does someone have an explanation for this ?

Bye,
Stefan



----- EXAMPLE 1

#!/usr/local/bin/perl -w

use strict;

my(@Array) = ('one', 'two', 'three', 'four', 'five', 'six');

my($element);
foreach $element ( grep(/^three$/,@Array) ) {
   $element =~ s/^three$/third/;
}

print join("\n",@Array), "\n";



----- EXAMPLE 2

#!/usr/local/bin/perl -w

use strict;

my(%List) = ('one', 1,  'two', 2,  'three', 3,  'four', 4,  'five', 5);

my($element);
foreach $element (keys %List) {
   $element =~ s/^three$/third/;
}

foreach $element (keys %List) {
   print $element, " = ", $List{$element}, "\n";
}




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

Date: 08 Feb 2003 16:32:50 GMT
From: "James E Keenan" <jkeen@concentric.net>
Subject: Re: Modify array elements using foreach ?
Message-Id: <b23bfi$l8a@dispatch.concentric.net>


"Stefan" <someone@somewhere.nl> wrote in message
news:3e452c55$0$150$e4fe514c@dreader8.news.xs4all.nl...
> Hello all,
>
> Something, I didnt notice before, is puzzling me. When stepping through
all
> elements in an array, changing the current element will automatically
update
> the array. Even if there is a grep involved (example 1). The same thing
but
> on an associative-array, does not seem to do that (example 2).
>
> Does someone have an explanation for this ?
>

Larry Wall does.  Programming Perl (3rd ed), p 34:
"[E]ach element of the list is aliased to the loop variable in turn, and the
block of code is executed once for each element.  Note that the loop
variable refers to the element itself, rather than a copy of the element.
Hence, modifying the loop variable also modifies the original array."




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

Date: 08 Feb 2003 16:54:56 GMT
From: "James E Keenan" <jkeen@concentric.net>
Subject: Re: Modify array elements using foreach ?
Message-Id: <b23cp0$21n@dispatch.concentric.net>


"James E Keenan" <jkeen@concentric.net> wrote in message
news:b23bfi$l8a@dispatch.concentric.net...
>
> "Stefan" <someone@somewhere.nl> wrote in message
> news:3e452c55$0$150$e4fe514c@dreader8.news.xs4all.nl...
>
> Larry Wall does.  Programming Perl (3rd ed), p 34:
> "[E]ach element of the list is aliased to the loop variable in turn, and
the
> block of code is executed once for each element.  Note that the loop
> variable refers to the element itself, rather than a copy of the element.
> Hence, modifying the loop variable also modifies the original array."
>
>
This is implied in 'perldoc perlsyn':  "The foreach loop iterates over a
normal list value and sets the variable VAR to be each element of the list
in turn."  But the explanation quoted from the Camel book is more complete.




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

Date: Sat, 8 Feb 2003 18:37:36 +0100
From: "Stefan" <someone@somewhere.nl>
Subject: Re: Modify array elements using foreach ?
Message-Id: <3e45405a$0$147$e4fe514c@dreader5.news.xs4all.nl>

"James E Keenan" <jkeen@concentric.net> schreef in bericht
news:b23cp0$21n@dispatch.concentric.net...
>
> "James E Keenan" <jkeen@concentric.net> wrote in message
> news:b23bfi$l8a@dispatch.concentric.net...
> >
> > "Stefan" <someone@somewhere.nl> wrote in message
> > news:3e452c55$0$150$e4fe514c@dreader8.news.xs4all.nl...
> >
> > Larry Wall does.  Programming Perl (3rd ed), p 34:
> > "[E]ach element of the list is aliased to the loop variable in turn, and
> the
> > block of code is executed once for each element.  Note that the loop
> > variable refers to the element itself, rather than a copy of the
element.
> > Hence, modifying the loop variable also modifies the original array."
> >
> >
> This is implied in 'perldoc perlsyn':  "The foreach loop iterates over a
> normal list value and sets the variable VAR to be each element of the list
> in turn."  But the explanation quoted from the Camel book is more
complete.


If you ask me, I'd say that 'perldoc perlsyn' is incomplete and only Larry
Wall has it right.

Part of my confusion was the fact that this referencing didnt seem to occur
on associative-arrays. Thats not completely true, the same thing happens
when stepping though the values. Nothing happens when stepping through the
keys, though. In the example below, the "0" isnt changed into "1" but the
value "three" is changed into "third".

It kind of makes sence now I know foreach uses references. And it actually
is quite powerfull since it isnt affected by greps. Still, I wonder why I
didnt notice before. Its more luck that wisdom my earlier scripts arent
showing any unexpected behaviour.

Oh, btw, thanks for your explanation. I think I'll get a copy of Larry
Wall's Perl guide. It really adds something to the existing documentation.

Bye,
Stefan


#!/usr/local/bin/perl -w

use strict;

my(%List) = (0, 'one',  2, 'two',  3, 'three',  4, 'four',  5, 'five');

my($element);

foreach $element (keys %List) {
   $element =~ s/^0$/1/;
}

foreach $element (values %List) {
   $element =~ s/^three$/third/;
}

foreach $element (keys %List) {
   print $element, " = ", $List{$element}, "\n";
}






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

Date: 08 Feb 2003 17:42:33 GMT
From: ctcgag@hotmail.com
Subject: Re: Modify array elements using foreach ?
Message-Id: <20030208124233.821$S5@newsreader.com>

"Stefan" <someone@somewhere.nl> wrote:
> Hello all,
>
> Something, I didnt notice before, is puzzling me. When stepping through
> all elements in an array, changing the current element will automatically
> update the array. Even if there is a grep involved (example 1). The same
> thing but on an associative-array, does not seem to do that (example 2).

That's because the keys of an associative array are not full perl
scalars, they are lightweight strings.  So "keys" cannot alias into the
keys, it has to copy them into real sv's.  The values return by "values",
on the other hand, are aliases.

> When checking the description of foreach, I could not find anything which
> explains this behaviour.

You mean this didn't tip you off:?

       If any element of LIST is an lvalue, you can modify it by
       modifying VAR inside the loop.  Conversely, if any element
       of LIST is NOT an lvalue, any attempt to modify that ele-
       ment will fail.  In other words, the "foreach" loop index
       variable is an implicit alias for each item in the list
       that you're looping over.


Xho

-- 
-------------------- http://NewsReader.Com/ --------------------
Usenet Newsgroup Service              New Rate! $9.95/Month 50GB


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

Date: Sat, 8 Feb 2003 18:51:30 +0100
From: "Stefan" <someone@somewhere.nl>
Subject: Re: Modify array elements using foreach ?
Message-Id: <3e45439b$0$144$e4fe514c@dreader5.news.xs4all.nl>

<ctcgag@hotmail.com> schreef in bericht
news:20030208124233.821$S5@newsreader.com...
> > When checking the description of foreach, I could not find anything
which
> > explains this behaviour.
>
> You mean this didn't tip you off:?
>
>        If any element of LIST is an lvalue, you can modify it by
>        modifying VAR inside the loop.  Conversely, if any element
>        of LIST is NOT an lvalue, any attempt to modify that ele-
>        ment will fail.  In other words, the "foreach" loop index
>        variable is an implicit alias for each item in the list
>        that you're looping over.


No it didnt and I didnt even notice the 2nd time I read it   :-/

   # perl -e 'foreach ('one','two','three') { s/one/1/; }'
  Modification of a read-only value attempted at -e line 1.

It all makes sence now. Contrairy to what I wrote in the other part of this
thread, 'perldoc perlsyn' *does* describe foreach correct.

Stefan




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

Date: 8 Feb 2003 21:08:36 GMT
From: "Tassilo v. Parseval" <tassilo.parseval@post.rwth-aachen.de>
Subject: Re: Modify array elements using foreach ?
Message-Id: <b23rkk$8p7$1@nets3.rz.RWTH-Aachen.DE>

Also sprach Stefan:

[ foreach changing arrays but not hash-keys ]

> Part of my confusion was the fact that this referencing didnt seem to occur
> on associative-arrays. Thats not completely true, the same thing happens
> when stepping though the values. Nothing happens when stepping through the
> keys, though. In the example below, the "0" isnt changed into "1" but the
> value "three" is changed into "third".

That has something to do with how Perl stores hash-keys. Not proper
scalar values but something in between. Also, if this changing on
hash-keys worked it would require rehashing of these keys.

> It kind of makes sence now I know foreach uses references. And it actually
> is quite powerfull since it isnt affected by greps. Still, I wonder why I
> didnt notice before. Its more luck that wisdom my earlier scripts arent
> showing any unexpected behaviour.

foreach does not involve references. The loop variable _aliases_ the
array element (and so do the elements of @_ in subroutines and $_ in
grep() and map()). It's like having two names for one thing. If they
were references you'd have to dereference them somehow which obviously
doesn't happen.

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: Sat, 08 Feb 2003 04:29:41 +1000
From: "Andrew Rich" <andrew.rich@bigpond.com>
Subject: MySQL DBI
Message-Id: <yGS0a.42799$jM5.108220@newsfeeds.bigpond.com>

Wondering if someone can help me.
I have the laptop running MySQL on port 3306
Trying to connect with the desktop, do a transaction and then disconnect.

error:

DBI->connect(database=logbook;host=192.168.0.3;port=3306) failed: Lost connection to MySQL server during query at ./mysql3306.pl line 9
Can't call method "prepare" on an undefined value at ./mysql3306.pl line 10.

code:

#!/usr/bin/perl
use DBI;
my $database_handler = DBI->connect("DBI:mysql:database=logbook;host=192.168.0.
3;port=3306","root","");
$statement_handler =$database_handler->prepare ("insert into information values
(\"title\",\"url\",\"description\",\"keywords\",\"date\")");
$statement_handler->execute;
$statement_handler->finish;

guess:

It is not firewall, iptables reports no chains

Cheers Andrew




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

Date: Fri, 07 Feb 2003 14:34:07 -0500
From: Benjamin Goldberg <goldbb2@earthlink.net>
Subject: Re: MySQL DBI
Message-Id: <3E440A2F.F7D800A9@earthlink.net>

Andrew Rich wrote:
> 
> Wondering if someone can help me.
> I have the laptop running MySQL on port 3306
> Trying to connect with the desktop, do a transaction and then
> disconnect.
> 
> error:
> 
> DBI->connect(database=logbook;host=192.168.0.3;port=3306) failed: Lost
> connection to MySQL server during query at ./mysql3306.pl line 9

This means that you failed to connect.

Go read the docs of MySQL, and find out what "Lost connection" means.

> Can't call method "prepare" on an undefined value at ./mysql3306.pl
> line 10.

This means that your program did not check whether or not the connect
succeeded, and attempted to use the undefined value returned by the
unsuccessfuly connect as if it were an actual, connected, database
handle.

[snip]
> guess:
> 
> It is not firewall, iptables reports no chains

Instead of guessing, read the documentation.  Failing that, try using
google to see if others have encountered the error, and see what they
did to fix it.

In any case, it's not a perl error, it's a MySQL error.

There's a newsgroup "mailing.database.mysql" on google which you might
try searching.

   http://groups.google.com/groups?
      q="Lost+connection+to+MySQL+server+during+query"

-- 
"So, who beat the clueless idiot today?"
"Well, we flipped for it, but when Kuno
 landed, he wasn't in any shape to fight."
"Next time, try flipping a *coin.*"


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

Date: Fri, 07 Feb 2003 15:19:43 -0600
From: Anthony Saffer <anthonysaffer@NOSPAM.yahoo.com>
Subject: Re: Need a bit of help with LWP
Message-Id: <rg884vgo87l9ebq0q2lohgmgrd60rv0g69@4ax.com>

<snip>
>Yes, there are many ways to search a "page" without using the
>getstore() method (is this the LWP one?) but no portable ones that you
>can use without downloading the data at all.

Yes, getstore() is an LWP method. But it actually downloads the entire
page to the hard disk which is what I was hoping to avoid.

>In other words: I am not entirely sure _what_ exactly you're trying to
>avoid. I'll assume that you are talking about LWP::Simple::getstore,
>and that you are trying to avoid storing the remote data on disk
>before using it. If that isn't right, please be more specific.

No, that's right...

>The LWP modules have many other methods available to get remote data
>over HTTP. The LWP::Simple module has several. I _think_ you're
>looking for LWP::Simple::get(), but who knows?

Using LWP::Simple::Get() sounded right when I was reading the
documentation. But I suppose I'm not understanding what the docs are
saying. For example, when I get() a page using this method, are the
contents then stored in an array? If so, then that is DEFINATELY what
I need. But the docs don't specify that.

>Do try to read the documentation for LWP::Simple and the lwpcook
>documentation. It's quite good.

Indeed I have read the documentation for the modules. I just don't
understand what they are saying. See my question above for a clarified
view.

Anthony


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

Date: 07 Feb 2003 15:08:22 -0700
From: Eric Schwartz <eric.schwartz@hp.com>
Subject: Re: Need a bit of help with LWP
Message-Id: <etowukb217t.fsf@wormtongue.emschwar>

Anthony Saffer <anthonysaffer@NOSPAM.yahoo.com> writes:
> Using LWP::Simple::Get() sounded right when I was reading the
> documentation. But I suppose I'm not understanding what the docs are
> saying. For example, when I get() a page using this method, are the
> contents then stored in an array? If so, then that is DEFINATELY what
> I need. But the docs don't specify that.

My copy of the docs says:

        use LWP::Simple;
        $content = get("http://www.sn.no/")

That seems pretty clear that get() returns a scalar.  If yours doesn't
have that bit, you might want to upgrade your perl distribution.

> Indeed I have read the documentation for the modules. I just don't
> understand what they are saying. See my question above for a clarified
> view.

What was unclear about the above?  If we know what's wrong we can try
and clear them up.  I'll admit the documentation for get() itself
could be clearer (it just says it 'return[s] it'), but I'd imagine
10-20 seconds of experimentation would yield more specific results:

$ perl -wM"LWP::Simple" -e 'my @ary = get("http://www.google.com/"); $"="]\n["; print "array: [@ary]\n";'

This prints only one [] pair, indicating there's only one entry in
@ary; thus get returns a scalar, as the documentation says.

-=Eric
-- 
Come to think of it, there are already a million monkeys on a million
typewriters, and Usenet is NOTHING like Shakespeare.
		-- Blair Houghton.


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

Date: Fri, 7 Feb 2003 16:19:46 -0600
From: tadmc@augustmail.com (Tad McClellan)
Subject: Re: Need a bit of help with LWP
Message-Id: <slrnb48c82.i45.tadmc@magna.augustmail.com>

Anthony Saffer <anthonysaffer@NOSPAM.yahoo.com> wrote:

> Using LWP::Simple::Get() sounded right 


No, it sounds non-existent.

Case matters.  :-)


> when I was reading the
> documentation. But I suppose I'm not understanding what the docs are
> saying. For example, when I get() a page using this method, are the
> contents then stored in an array? 


No, they are stored in a scalar, as shown in the SYNOPSIS:

   $content = get("http://www.sn.no/")


Why would an array be better? 

How would the page be split up into array elements?


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


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

Date: 7 Feb 2003 14:18:07 -0800
From: jcapenos@yahoo.com (J Capenos)
Subject: Need to order alpha numeric codes with Perl/Mysql
Message-Id: <f417bbc8.0302071418.40e348f3@posting.google.com>

I am having some trouble ordering numeric codes with a mysql database.

We have a system designed in Perl that we need to accept item #'s like
1, 1a, 2, 2a and have them order in that way.

Are there any libraries out there or possibly some code someone has
developed to help?

Thanks


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

Date: Fri, 7 Feb 2003 17:19:03 -0600
From: tadmc@augustmail.com (Tad McClellan)
Subject: Re: Need to order alpha numeric codes with Perl/Mysql
Message-Id: <slrnb48fn7.i8v.tadmc@magna.augustmail.com>

J Capenos <jcapenos@yahoo.com> wrote:

> We have a system designed in Perl that we need to accept item #'s like
> 1, 1a, 2, 2a and have them order in that way.
> 
> Are there any libraries out there or possibly some code someone has
> developed to help?


Your Question is Asked Frequently:

   perldoc -q sort

      "How do I sort an array by (anything)?"

Take the Schwartzian Transform given in the FAQ answer,
and modify it to fit your situation:

--------------------------------
#!/usr/bin/perl
use strict;
use warnings;

my @data = qw/ 1 2 2a 1a 3a 3 2b 1c /;

my @sorted = map  { $_->[0] }
             sort { $a->[1] <=> $b->[1] or
                    $a->[2] cmp $b->[2]
                  }
             map  { [ $_, /(\d+)([a-z]*)/g ] } @data;

print "$_\n" for @sorted;
--------------------------------


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


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

Date: Fri, 07 Feb 2003 23:56:03 -0500
From: Benjamin Goldberg <goldbb2@earthlink.net>
Subject: Re: Need to order alpha numeric codes with Perl/Mysql
Message-Id: <3E448DE3.B8A24CBC@earthlink.net>

Tad McClellan wrote:
[snip]
> my @sorted = map  { $_->[0] }
>              sort { $a->[1] <=> $b->[1] or
>                     $a->[2] cmp $b->[2]
>                   }
>              map  { [ $_, /(\d+)([a-z]*)/g ] } @data;

Two notes:

First, using a BLOCK instead of an EXPR with map is slower.

Second, there's no need for /g on the regex.

-- 
"So, who beat the clueless idiot today?"
"Well, we flipped for it, but when Kuno
 landed, he wasn't in any shape to fight."
"Next time, try flipping a *coin.*"


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

Date: 08 Feb 2003 23:27:00 GMT
From: Abigail <abigail@abigail.nl>
Subject: Re: Need to order alpha numeric codes with Perl/Mysql
Message-Id: <slrnb4b4i4.sb.abigail@alexandra.abigail.nl>

Benjamin Goldberg (goldbb2@earthlink.net) wrote on MMMCDXLVIII September
MCMXCIII in <URL:news:3E448DE3.B8A24CBC@earthlink.net>:
$$  Tad McClellan wrote:
$$  [snip]
$$ > my @sorted = map  { $_->[0] }
$$ >              sort { $a->[1] <=> $b->[1] or
$$ >                     $a->[2] cmp $b->[2]
$$ >                   }
$$ >              map  { [ $_, /(\d+)([a-z]*)/g ] } @data;
$$  
$$  Two notes:
$$  
$$  First, using a BLOCK instead of an EXPR with map is slower.

First, using Perl instead of C is slower.



Abigail
-- 
perl -e '* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
         / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / 
         % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %;
         BEGIN {% % = ($ _ = " " => print "Just Another Perl Hacker\n")}'


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

Date: Sun, 09 Feb 2003 05:51:19 GMT
From: Andrew Lee <spamtrap@nowhere.com>
Subject: Re: Need to order alpha numeric codes with Perl/Mysql
Message-Id: <cc3q1vsb8rvp59botu2526r69euo5811hn@4ax.com>

On 08 Feb 2003 23:27:00 GMT, Abigail <abigail@abigail.nl> wrote:

>Benjamin Goldberg (goldbb2@earthlink.net) wrote on MMMCDXLVIII September
>MCMXCIII in <URL:news:3E448DE3.B8A24CBC@earthlink.net>:
>$$  Tad McClellan wrote:
>$$  [snip]
>$$ > my @sorted = map  { $_->[0] }
>$$ >              sort { $a->[1] <=> $b->[1] or
>$$ >                     $a->[2] cmp $b->[2]
>$$ >                   }
>$$ >              map  { [ $_, /(\d+)([a-z]*)/g ] } @data;
>$$  
>$$  Two notes:
>$$  
>$$  First, using a BLOCK instead of an EXPR with map is slower.
>
>First, using Perl instead of C is slower.
>
>
$ time perl -e 'for (0..999){print `./hello`}'
real    0m15.951s
user    0m23.280s
sys     0m9.311s

$ time perl -e 'for (0..999){print `./hello.pl`}'
real    0m16.976s
user    0m24.030s
sys     0m9.461s

not much of a difference ... depends on the task.


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

Date: 9 Feb 2003 07:20:24 GMT
From: "Tassilo v. Parseval" <tassilo.parseval@post.rwth-aachen.de>
Subject: Re: Need to order alpha numeric codes with Perl/Mysql
Message-Id: <b24vfo$pj4$1@nets3.rz.RWTH-Aachen.DE>

Also sprach Andrew Lee:

> On 08 Feb 2003 23:27:00 GMT, Abigail <abigail@abigail.nl> wrote:

>>First, using Perl instead of C is slower.
>>
>>
> $ time perl -e 'for (0..999){print `./hello`}'
> real    0m15.951s
> user    0m23.280s
> sys     0m9.311s
> 
> $ time perl -e 'for (0..999){print `./hello.pl`}'
> real    0m16.976s
> user    0m24.030s
> sys     0m9.461s
> 
> not much of a difference ... depends on the task.

This benchmark doesn't have a lot of significance. You probably have an
overhead of 90% simply by spawning a new process a 1000 times. Instead
move the for-loop into the C programm and Perl script respectively and
you'll get a larger gap.

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: 8 Feb 2003 20:27:24 -0800
From: amanda@capturinglight.com (Felini)
Subject: need to recreate an awk script in Perl
Message-Id: <6918f270.0302082027.57d3e0bb@posting.google.com>

I have a awk script that i need to recreate in Perl.  I am not sure
where to begin because i am new to Perl, so hopefully someone can
help.

This was my first awk script, so i am glad it works... My awk script
does this:

analyzes a password file (called 'ourpasswd'), strips out the 5th
field (the username), strips out the blank lines (some lines do not
have usernames), finds all the duplicate usernames... etc. etc.  and
at the end, prints "total number of records", "percentage of records
corresponding to duplicates in total number of records", and
"duplicated usernames with # of records each".

$ nawk -F: -f asg6.awk ourpasswd

################# asg6.awk #################################
#!/usr/bin/perl

BEGIN {
   while (getline var<"usernames")
   table [var] = 0
}

{
   if ($5 != "")
   table [$5]++

}

END {
   print "Total number of records = " NR
   for (name in table)
   {
     if (table[name]>1)
     {
       numduplines += table[name]
       percent = numduplines/NR*100
     }
   }                                    

print "The percentage of duplicate records: " percent"%"

   for (name in table)
   {
     if (table[name]>1)
    {
    print "Duplicated name and # of records: " name, table[name]
    }
   }
} 
#############################################


Now...  how in the world do i do the same thing in Perl;  using a
'hash table,' the 'open' operation, the 'split' command, an array
called "line", and scalar variables?

The script should produce the same results above...  

so far...  this is all i have...  


#############  asg6.pl ##################


#!/usr/bin/perl 

open  (USERS, "usernames") or die "Can't read usernames.\n"; 

while ($current_line = <USERS>) { 

      chomp ($current_line); 

      print "Current line is $current_line.\n"; 

    } 

close USERS; 

open (USERS2, "ourpasswd") or die "Can't read ourpasswd.\n"; 

while ($current_line2 = <USERS2>) { 

      @line = split(/:/, $current_line2); 

      print @line; 

     } 

close USERS2;   

#########################


Thanks for any tips you can offer,
Amanda


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

Date: 09 Feb 2003 04:54:30 GMT
From: "James E Keenan" <jkeen@concentric.net>
Subject: Re: need to recreate an awk script in Perl
Message-Id: <b24mu6$285@dispatch.concentric.net>


"Felini" <amanda@capturinglight.com> wrote in message
news:6918f270.0302082027.57d3e0bb@posting.google.com...
> I have a awk script that i need to recreate in Perl.  I am not sure
> where to begin because i am new to Perl, so hopefully someone can
> help.
>
> analyzes a password file (called 'ourpasswd'), strips out the 5th
> field (the username), strips out the blank lines (some lines do not
> have usernames), finds all the duplicate usernames... etc. etc.  and
> at the end, prints "total number of records", "percentage of records
> corresponding to duplicates in total number of records", and
> "duplicated usernames with # of records each".
>
> $ nawk -F: -f asg6.awk ourpasswd
>
> ################# asg6.awk #################################
> #!/usr/bin/perl
>
> BEGIN {
>    while (getline var<"usernames")
>    table [var] = 0
> }
>
> {
>    if ($5 != "")
>    table [$5]++
>
> }
>
> END {
>    print "Total number of records = " NR
>    for (name in table)
>    {
>      if (table[name]>1)
>      {
>        numduplines += table[name]
>        percent = numduplines/NR*100
>      }
>    }
>
> print "The percentage of duplicate records: " percent"%"
>
>    for (name in table)
>    {
>      if (table[name]>1)
>     {
>     print "Duplicated name and # of records: " name, table[name]
>     }
>    }
> }
> #############################################
>
> #############  asg6.pl ##################
>
>
> #!/usr/bin/perl
>
> open  (USERS, "usernames") or die "Can't read usernames.\n";
>
> while ($current_line = <USERS>) {
>
>       chomp ($current_line);
>
>       print "Current line is $current_line.\n";
>
>     }
>
> close USERS;
>
Your written description of the task suggests that you have to analyze only
*one* file ("ourpasswd").  If so, then what are you doing opening a
filehandle to a different file ("usernames")?  Wouldn't user names be part
of the password file?  If so, then I don't see what the point of the
preceding Perl code is; only what follows is relevant.

Here's some rough code (untested):

my (%usernames, %dupe_usernames);   # hashes ... not hash tables
my ($count);
open (USERS2, "ourpasswd") or die "Can't read ourpasswd.\n";
while (my $current_line2 = <USERS2>) {
       next if ($current_line2 =~ /^\s+$/);   # strip out blank lines
       next if ($current_line2 =~ /^#/);        # strip out lines holding
only comments
       my @line = split(/:/, $current_line2);
       $usernames{$line[4]}++ if (defined $line[4]);
        $count++;
}
> close USERS2;
foreach (keys %usernames) {
    %dupe_usernames{$_} = $usernames{$_} if $usernames{$_}>1;
}

 .... and you can take it from there.




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

Date: Sun, 09 Feb 2003 06:24:02 GMT
From: Steven Smolinski <steven.smolinski@sympatico.ca>
Subject: Re: need to recreate an awk script in Perl
Message-Id: <6um1a.7149$Zt4.1314067@news20.bellglobal.com>

Felini <amanda@capturinglight.com> wrote:
> I have a awk script that i need to recreate in Perl.

man a2p

HTH.

Steve
-- 
Steven Smolinski => http://arbiter.ca/
GnuPG Public Key => http://arbiter.ca/steves_public_key.txt
                 => or email me with 'auto-key' in the subject.
Key Fingerprint  => 08C8 6481 3A7B 2A1C 7C26  A5FC 1A1B 66AB F637 495D


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

Date: Sun, 09 Feb 2003 12:47:39 GMT
From: "John W. Krahn" <krahnj@acm.org>
Subject: Re: need to recreate an awk script in Perl
Message-Id: <3E464DC3.35C3FC72@acm.org>

Felini wrote:
> 
> I have a awk script that i need to recreate in Perl.  I am not sure
> where to begin because i am new to Perl, so hopefully someone can
> help.
> 
> This was my first awk script, so i am glad it works... My awk script
> does this:
> 
> analyzes a password file (called 'ourpasswd'), strips out the 5th
> field (the username), strips out the blank lines (some lines do not
> have usernames), finds all the duplicate usernames... etc. etc.  and
> at the end, prints "total number of records", "percentage of records
> corresponding to duplicates in total number of records", and
> "duplicated usernames with # of records each".
> 
> $ nawk -F: -f asg6.awk ourpasswd
> 
> ################# asg6.awk #################################
> #!/usr/bin/perl
> 
> BEGIN {
>    while (getline var<"usernames")
>    table [var] = 0
> }

The contents of "usernames" are not useful to your program because you are
setting the values to zero but you are only using elements of table that have
a value greater than one.


> {
>    if ($5 != "")
>    table [$5]++
> 
> }
> 
> END {
>    print "Total number of records = " NR
>    for (name in table)
>    {
>      if (table[name]>1)
>      {
>        numduplines += table[name]
>        percent = numduplines/NR*100
>      }
>    }
> 
> print "The percentage of duplicate records: " percent"%"
> 
>    for (name in table)
>    {
>      if (table[name]>1)
>     {
>     print "Duplicated name and # of records: " name, table[name]
>     }
>    }
> }
> #############################################
> 
> Now...  how in the world do i do the same thing in Perl;  using a
> 'hash table,' the 'open' operation, the 'split' command, an array
> called "line", and scalar variables?
> 
> The script should produce the same results above...
> 
> Thanks for any tips you can offer,

To do the same thing in perl (save to a file and run as "$ asg6.pl ourpasswd")

#!/usr/bin/perl

my %table;

# if you REALLY need the contents of
# 'usernames' uncomment the next two lines
#open my $fh, 'usernames' or die "Cannot open file 'usernames' $!";
#@table{ split ' ', do { local $/; <$fh> } } = undef;

( my $fld = (split /:/)[ 4 ] ) ne ''
    and $table{ $fld }++
        while <>;

print "Total number of records = $.\n";

my $numduplines;
$_ > 1 and $numduplines += $_ for values %table;

my $percent = $numduplines / $. * 100;

print "The percentage of duplicate records: $percent%\n";

$table{ $_ } > 1
    and print "Duplicated name and # of records: $_ $table{$_}\n"
        for keys %table;

__END__



John
-- 
use Perl;
program
fulfillment


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

Date: Sun, 09 Feb 2003 23:08:47 -0500
From: Benjamin Goldberg <goldbb2@earthlink.net>
Subject: Re: need to recreate an awk script in Perl
Message-Id: <3E4725CF.3C2B4B8A@earthlink.net>

Felini wrote:
[snip]
Well, translating as closely as possibly (but changing awk idioms to
perl idioms where possible):

#!/usr/bin/perl -F: -ln
++$table{$F[4]} if $F[4];
END {
   print "Total number of records = ", $.;
   while( my ($name, $count) = each %table ) {
      next if $count < 2;
      $numduplines += $count;
   }
   $percent = $numduplines / $. * 100;
   print "The percentage of duplicate records: ", $percent;
   while( my ($name, $count) = each %table ) {
      next if $count < 2;
      print "Duplicated name and # of records: ", $name, " ", $count;
   }
}
__END__

[untested]

-- 
"So, who beat the clueless idiot today?"
"Well, we flipped for it, but when Kuno
 landed, he wasn't in any shape to fight."
"Next time, try flipping a *coin.*"


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

Date: Mon, 10 Feb 2003 05:41:51 GMT
From: "John W. Krahn" <krahnj@acm.org>
Subject: Re: need to recreate an awk script in Perl
Message-Id: <3E473B75.9C00A0A7@acm.org>

Benjamin Goldberg wrote:
> 
> Felini wrote:
> [snip]
> Well, translating as closely as possibly (but changing awk idioms to
> perl idioms where possible):
> 
> #!/usr/bin/perl -F: -ln

You need the -a option to get the current line split into @F.

#!/usr/bin/perl -F: -lan


> ++$table{$F[4]} if $F[4];


John
-- 
use Perl;
program
fulfillment


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

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


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