[23209] in Perl-Users-Digest

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

Perl-Users Digest, Issue: 5430 Volume: 10

daemon@ATHENA.MIT.EDU (Perl-Users Digest)
Tue Sep 2 18:05:45 2003

Date: Tue, 2 Sep 2003 15:05:08 -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           Tue, 2 Sep 2003     Volume: 10 Number: 5430

Today's topics:
    Re: A few questions about Perl and it's capabilities <minceme@start.no>
    Re: A few questions about Perl and it's capabilities <minceme@start.no>
    Re: Calling perl built-in functions <shawn@magma.ca>
    Re: can't redirect output to a file?! (Greg Bacon)
    Re: can't redirect output to a file?! <krahnj@acm.org>
    Re: can't redirect output to a file?! <bharnish@technologist.com>
    Re: Cant it be done?? <cs@edu.edu>
    Re: Cant it be done?? <postmaster@castleamber.com>
        checking whether user browser has cookies turned on? (Kenjis Kaan)
    Re: checking whether user browser has cookies turned on <spam@thecouch.homeip.net>
    Re: Comments in templates for pack() <wwonko@rdwarf.com>
    Re: Extra carriage returns - why? <wwonko@rdwarf.com>
    Re: Help -- how to execute "computed Perl code" <bart.lateur@pandora.be>
    Re: how to name an array such that it can include a var (Jonas Yorg)
    Re: Perl 5.6 - Multithreaded ??? <wwonko@rdwarf.com>
    Re: Perl Debugger, Windows NT and BSODs <wwonko@rdwarf.com>
        Problem with Date::Manip, taint mode, and CGI::Carp. <wwonko@rdwarf.com>
    Re: Reading a scalar line by line <krahnj@acm.org>
    Re: Replacing IP's in ./etc/hosts <krahnj@acm.org>
    Re: Silly push tricks <shawn@magma.ca>
    Re: Silly push tricks <tore@aursand.no>
        Why qr// needs /o modifier, or bug in a documentation. <this.is.invalid@yahoo.com>
    Re: write hex to socket, weird <krahnj@acm.org>
    Re:  <bwalton@rochester.rr.com>
        Digest Administrivia (Last modified: 6 Apr 01) (Perl-Users-Digest Admin)

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

Date: Tue, 2 Sep 2003 19:29:28 +0000 (UTC)
From: Vlad Tepes <minceme@start.no>
Subject: Re: A few questions about Perl and it's capabilities
Message-Id: <bj2r2o$4eb$1@troll.powertech.no>

Benjamin Goldberg <ben.goldberg@hotpop.com> wrote:

> Vlad Tepes wrote:
>
>>     sub cursor($) {
>>         require Term::Cap;
>>         Term::Cap->Tgetent->Tputs( $_[0] ? 've' : 'vi', 0, *STDOUT );
>>     }
>
> It would be more efficient to change this to:
>
>      my $cap;
>      sub cursor($) {
>          $cap ||= (require Term::Cap and Term::Cap->Tgetent);
>          $cap->Tputs( $_[0] ? 've' : 'vi', 0, *STDOUT );
>      }
>
> I mean, why bother re-calling Tgetent each time you want to make the
> cursor appear or dissappear?

Well, as I said, the script was just thrown together. I scanned the docs
and /etc/termcap and was satisfied once it was working.

I agree, catching is a good idea. On my machine your version saves
some 7 ms on repeated calls to cursor().  Jippi! :-)

Thanks for the tip on Term::Cap, it might be useful sometime.

-- 
Vlad



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

Date: Tue, 2 Sep 2003 19:37:08 +0000 (UTC)
From: Vlad Tepes <minceme@start.no>
Subject: Re: A few questions about Perl and it's capabilities
Message-Id: <bj2rh4$4kh$1@troll.powertech.no>

Benjamin Goldberg <ben.goldberg@hotpop.com> wrote:

> Vlad Tepes wrote:
>
>>     sub cursor($) {
>>         require Term::Cap;
>>         Term::Cap->Tgetent->Tputs( $_[0] ? 've' : 'vi', 0, *STDOUT );
>>     }
>
> It would be more efficient to change this to:
>
>      my $cap;
>      sub cursor($) {
>          $cap ||= (require Term::Cap and Term::Cap->Tgetent);
>          $cap->Tputs( $_[0] ? 've' : 'vi', 0, *STDOUT );
>      }
>
> I mean, why bother re-calling Tgetent each time you want to make the
> cursor appear or dissappear?

Well, as I said, the script was just thrown together. I scanned the docs
and /etc/termcap and was satisfied once it was working.

I agree, catching is a good idea. On my machine your version saves
some 7 ms on repeated calls to cursor().  Jippi! :-)

Thanks for the tip on Term::Cap, it might be useful sometime.

-- 
Vlad



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

Date: Tue, 02 Sep 2003 14:34:50 -0400
From: Shawn Corey <shawn@magma.ca>
Subject: Re: Calling perl built-in functions
Message-Id: <Bnudneqilrc3f8miXTWJkA@magma.ca>

Uri Guttman wrote:

>>>>>>"SC" == Shawn Corey <shawn@magma.ca> writes:
> 
> 
>   SC>  From my bag of dirty tricks:
> 
> very dirty.
> 
>   SC> #!/usr/bin/perl
> 
>   SC> $function='print';
> 
>   SC> &$function("Hello, world\n");
> 
>   SC> sub print {
>   SC>    print @_;
>   SC> }
> 
> try that under use strict.
> 
> next!!
> 
> uri
> 
I didn't say it was good programming pratice; in fact, I called it a 
dirty trick.



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

Date: Tue, 02 Sep 2003 18:06:34 -0000
From: gbacon@hiwaay.net (Greg Bacon)
Subject: Re: can't redirect output to a file?!
Message-Id: <vl9n1ao2qmss54@corp.supernews.com>

In article <bj2dh5$1be4$1@malibu.unice.fr>,
    Damien Mattei  <mattei@unice.fr> wrote:

: [...]
:
: it works like that:
: 
: cat ../var/oui.txt | ./preformat.pl
: 
: but when i try this:
: 
: cat ../var/oui.txt | ./preformat.pl > ../var/ieee_ethercodes.dat
: Value of <HANDLE> construct can be "0"; test with defined() at 
: ./preformat.pl line 56.
: 
: line 56 is this one : while (($oneline = <STDIN>) && ($oneline !~ 
: /^\n$/)) {

The warning is there in both cases, but redirecting stdout makes it
more obvious.  The fix is to add a defined test:

    while (defined($oneline = <STDIN>) && ($oneline !~ /^\n$/)) {

Below is a suggestion for further simplifying your code:

    #! /usr/local/bin/perl

    use strict;
    use warnings;

    # split1line (read split first line)
    # read this: 00-00-00   (hex)           CORPORATION NAME
    # return that: 000000   CORPORATION NAME

    sub next_pair {
        local $/ = "";

        my $h = qr/[A-Fa-f0-9][A-Fa-f0-9]/;

        RECORD: {
            local $_ = <>;
            return unless defined $_;

            redo if /^\s*OUI\b/;

            unless (/^($h)-($h)-($h)\s+\(hex\)\s+(.+?)\n/s) {
                warn "$0: record $.: no match";
                return;
            }

            return "$1$2$3", $4;
        }
    }

    while (my($ethercode, $vendor) = next_pair) {
         print $ethercode, "\t", $vendor, "\n";
    }

Hope this helps,
Greg
-- 
You've got to understand their market has always been the Windows space,
where you're actually doing people a favor by charging them money for
things, because that's the only way to keep from confusing them.
    -- Larry Wall on ActiveState


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

Date: Tue, 02 Sep 2003 18:21:38 GMT
From: "John W. Krahn" <krahnj@acm.org>
Subject: Re: can't redirect output to a file?!
Message-Id: <3F54DFA0.526A4200@acm.org>

Damien Mattei wrote:
> 
> [snip]
> 
> it works like that:
> 
> cat ../var/oui.txt | ./preformat.pl
> 
> but when i try this:
> 
> cat ../var/oui.txt | ./preformat.pl > ../var/ieee_ethercodes.dat
> Value of <HANDLE> construct can be "0"; test with defined() at
> ./preformat.pl line 56.
> 
> line 56 is this one : while (($oneline = <STDIN>) && ($oneline !~
> /^\n$/)) {

In older versions of Perl you had to explicitly test for definedness if
you were assigning from <> in scalar context.

while ( defined( $oneline = <STDIN> ) && ( $oneline !~ /^\n$/ ) ) {

Or:

while ( defined( $oneline = <STDIN> ) ) {
    next unless $oneline =~ /./;




John
-- 
use Perl;
program
fulfillment


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

Date: Tue, 02 Sep 2003 18:28:44 GMT
From: Brian Harnish <bharnish@technologist.com>
Subject: Re: can't redirect output to a file?!
Message-Id: <pan.2003.09.02.18.29.02.732642@technologist.com>

-----BEGIN xxx SIGNED MESSAGE-----
Hash: SHA1

On Tue, 02 Sep 2003 17:30:51 +0200, Damien Mattei wrote:

> i wrote a simple program that read data from STDIN  but redirected in a 
> pipe  from a file parse it and wrote output to STDOUT,here is the code:
[snip script...]
> it works like that:
> 
> cat ../var/oui.txt | ./preformat.pl
> 
> but when i try this:
> 
> cat ../var/oui.txt | ./preformat.pl > ../var/ieee_ethercodes.dat
> Value of <HANDLE> construct can be "0"; test with defined() at 
> ./preformat.pl line 56.
> 
> 
> line 56 is this one : while (($oneline = <STDIN>) && ($oneline !~ 
> /^\n$/)) {

Yes, its a good warning. What happens to your while loop if a line of
stdin matches /^0$/? Answer: the while expression stops. You can get a
better explanation if you also "use diagnostics;". $oneline = <STDIN> will
assign zero to $oneline. The value of $oneline will be returned to the
while, which will interpret that as boolean, and loop stops.

Also, your code is huge. Try this:
#!/usr/bin/perl -w
use strict;

$_ = <> for(1..6); #skip first 6 lines;

while(defined($_ = <>)) {
        chomp;

        # Seperate fields by whitespace (except the name)
        my @fields = split /\s+/, $_, 3;
        my @hex = split /-/, $fields[0];
        print join('',@hex), "\t", $fields[2], $/;

        # Skip until next blank line
        $_ = <> until(!defined($_) || /^$/);
}
__END__

 - Brian

-----BEGIN xxx SIGNATURE-----
Version: GnuPG v1.2.2 (GNU/Linux)

iD8DBQE/VOFHiK/rA3tCpFYRAmjEAKDg1mKZ3oe5R0RAl+Pkrm7/lUk2ZwCfUQxJ
o2fyWo2qotinaJ2swI35CP0=
=38r8
-----END PGP SIGNATURE-----



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

Date: Tue, 02 Sep 2003 11:14:36 -0700
From: Chief Squawtendrawpet <cs@edu.edu>
Subject: Re: Cant it be done??
Message-Id: <3F54DE0C.B6B0E06D@edu.edu>

Steve wrote:
> Have got this niggly reg ex qvestion.  I refuse to accept this can't
> be done with a single regex, but can't see a way at the moment.

Maybe not what you had in mind, but how about a single regex taking
advantage of the /g option?

$^W = 1;
use strict;
my (@block);

for my $datetime (<DATA>){
    @block = ();
    $block[$1] = $2 while $datetime =~ /(\d)(\d{4})/g;

    # Check results.
    print $datetime;
    for (1..5){
        print "  $_ = $block[$_]\n" if defined $block[$_];
    }
}

__END__
13112 22003 31143 42331 53651
13112 22003 31143 53651
13112 31143 42331
42331 53651


Here's the output:

13112 22003 31143 42331 53651
  1 = 3112
  2 = 2003
  3 = 1143
  4 = 2331
  5 = 3651
13112 22003 31143 53651
  1 = 3112
  2 = 2003
  3 = 1143
  5 = 3651
13112 31143 42331
  1 = 3112
  3 = 1143
  4 = 2331
42331 53651
  4 = 2331
  5 = 3651


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

Date: Tue, 02 Sep 2003 20:30:07 +0200
From: John Bokma <postmaster@castleamber.com>
Subject: Re: Cant it be done??
Message-Id: <3f54e211$0$196$58c7af7e@news.kabelfoon.nl>

Chief Squawtendrawpet wrote:

> Steve wrote:
> 
>>Have got this niggly reg ex qvestion.  I refuse to accept this can't
>>be done with a single regex, but can't see a way at the moment.
> 
> 
> Maybe not what you had in mind, but how about a single regex taking
> advantage of the /g option?
> 
> $^W = 1;
> use strict;
> my (@block);
> 
> for my $datetime (<DATA>){
>     @block = ();
>     $block[$1] = $2 while $datetime =~ /(\d)(\d{4})/g;

%hash = ()
$hash{$1} = $2 while ...

> 
>     # Check results.
>     print $datetime;
>     for (1..5){
>         print "  $_ = $block[$_]\n" if defined $block[$_];
>     }

foreach my $key (sort { $a <=> $b } keys %$hash) {
	print " $key = $hash{$key}\n";
}

not tested

-- 
Kind regards,       feel free to mail: mail(at)johnbokma.com (or reply)
                     virtual home: http://johnbokma.com/  ICQ: 218175426
John                web site hints: http://johnbokma.com/websitedesign/



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

Date: 2 Sep 2003 13:23:59 -0700
From: tivolinewbie@canada.com (Kenjis Kaan)
Subject: checking whether user browser has cookies turned on?
Message-Id: <6a8ba9f8.0309021223.30fdcecb@posting.google.com>

I am developing a web application that make use of the user browser's
cookies
mechanism.  Specifically my application will try to retrieve a session
key from the user's browser.  However I have a problem.  My program
doesn't know how to handle the case when the user's browser has the
cookies mechanism turned OFF!
This is because I don't know how to find out from perl code whether
the user's browser has cookies turned off or on?? I am using CGI.pm
Any ideas how to solve this problem?


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

Date: Tue, 02 Sep 2003 16:52:39 -0400
From: Mina Naguib <spam@thecouch.homeip.net>
Subject: Re: checking whether user browser has cookies turned on?
Message-Id: <yq75b.49565$fQ3.1202445@weber.videotron.net>

-----BEGIN xxx SIGNED MESSAGE-----
Hash: SHA1

Kenjis Kaan wrote:
> I am developing a web application that make use of the user browser's
> cookies
> mechanism.  Specifically my application will try to retrieve a session
> key from the user's browser.  However I have a problem.  My program
> doesn't know how to handle the case when the user's browser has the
> cookies mechanism turned OFF!
> This is because I don't know how to find out from perl code whether
> the user's browser has cookies turned off or on?? I am using CGI.pm
> Any ideas how to solve this problem?

First hit to the site:
1. Send test cookie
2. Send page that re-directs (via meta-refresh and/or javascript) to a cookie-checker CGI
3. In the CGI, check to see if test cookie was received or not.  Output another redirect to your 
site's main page (via HTTP Location: header) on success, or an error message/apology/instructions on 
failure.


-----BEGIN xxx SIGNATURE-----
Version: GnuPG v1.2.1 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQE/VQMfeS99pGMif6wRAi/SAKDqkew0sSP8KG8LglZE01xXfV36FACg83pj
VNGW/XtH2We1mhl1KtbhJ1M=
=+zfg
-----END PGP SIGNATURE-----



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

Date: Fri, 29 Aug 2003 18:59:37 +0000 (UTC)
From: Louis Erickson <wwonko@rdwarf.com>
Subject: Re: Comments in templates for pack()
Message-Id: <bio7qp$j0i$1@holly.rdwarf.com>

Vlad Tepes <minceme@start.no> wrote:
: John W. Krahn <krahnj@acm.org> wrote:
:> Vlad Tepes wrote:
:>> 
:>> 
:>>         my $packed = pack "l/A*             # field "firstwd"
:>                             ^                         ^   ^   ^
:>                             |                         |   |     \
:>                             String start     String end-Bareword-String start
:>
:>>                            A*",
:>                                ^
:>                                |
:>                                String end
:>
:>>                           "firstwd",
:>>                           "secondwd";
:>> 
:>> 
:>> While hardly a problem, it is unexpected behaviour. I thought
:>> everything after the comment-character would be ignored.
:>
:> It is completely expected that the first unescaped quote after the
:> starting quote will mark the end of the string.  How is perl supposed
:> to determine that the quote is not the end of the string?

: So it's the pack()-function that interprets the hash-character as
: start-of-comment, and not the tokenizer.

No, not at all.  If you say:

print "This is a message.                     # "Fooey!"
And this isn't really the end.";

Then you'll have the same issue.  Your string happens to include a # sign.
There's no comment there.  It's just a string.  # doesn't mean anything
special in a quoted string.

If your # sign was outside the string, then it would be correctly viewed
as a comment.

(Myself, I find multi-line strings almost universally hard to read.)

-- 
Louis Erickson - wwonko@rdwarf.com - http://www.rdwarf.com/~wwonko/

To the systems programmer, users and applications serve only to provide
a test load.


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

Date: Fri, 29 Aug 2003 17:24:42 +0000 (UTC)
From: Louis Erickson <wwonko@rdwarf.com>
Subject: Re: Extra carriage returns - why?
Message-Id: <bio28q$c8u$1@holly.rdwarf.com>

John Andrews <john.andrews1@talk21.com> wrote:
: Running  perl, v5.6.1 (built for cygwin-multi) on Win2000

Your file has Windows carriage returns, and your Perl is expecting Unix
carriage returns.  Cygwin does that.

Use a native Windows Perl (such as ActiveState) or convert the text file
to Unix carriage returns, or make your perl script smart enough to cope
with either kind of carriage return.

-- 
Louis Erickson - wwonko@rdwarf.com - http://www.rdwarf.com/~wwonko/

The goal of science is to build better mousetraps.  The goal of nature
is to build better mice.


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

Date: Tue, 02 Sep 2003 21:42:48 GMT
From: Bart Lateur <bart.lateur@pandora.be>
Subject: Re: Help -- how to execute "computed Perl code"
Message-Id: <ij3alvc7d038kqm04jmgs6h5nsdu85uq4h@4ax.com>

Steve D wrote:

>My code dynamically creates a scalar with a text string that is a
>valid Perl code line.
>
>How can I get Perl to execute the line contained in that scalar?
>
>I could write it to a temp file and then "do <file>", but I want to
>avoid that overhead.  It does not seem eval and "do BLOCK" are the
>answer.

"eval" it is.

	$string = 'print 3+3;';
	print "Let's do it:\n";
	eval $string;

Saving it to a temp file and then run "do $file;" would indeed do pretty
much the same.
	
-- 
	Bart.


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

Date: 2 Sep 2003 13:09:37 -0700
From: snikt@cyberspace.org (Jonas Yorg)
Subject: Re: how to name an array such that it can include a variable (for incrementing)
Message-Id: <c568c5cc.0309021209.4bafd7b2@posting.google.com>

>   JY> that's why I want to do it Abigail, but others have already been more
>   JY> helpful anyway.
> 
> and you still want to do it the wrong way? then they didn't help enough.
> 
no, the people who are actually helpful gave me a good way to do it,
where did I ever say that I was still doing it that way?  I was merely
saying that it's pointless to pretend to help when other people have
already given solutions.

You are suffering from the same impedement, you are posting nothing
that helps, and you're not even really giving new information, you're
just trying to feel superior which is fine because I am just learning
perl and I don't care that you know more about it than me.


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

Date: Thu, 28 Aug 2003 15:43:02 +0000 (UTC)
From: Louis Erickson <wwonko@rdwarf.com>
Subject: Re: Perl 5.6 - Multithreaded ???
Message-Id: <bil7u6$3g3$1@holly.rdwarf.com>

Greg Patnude <gpatnude@adelphia.net> wrote:
: My neighbor killed my NT box the other day by dropping a tree with a
: chainsaw onto the power lines and my UPS didn't kick in.... Really bummed...

Ouch!  That's a bummer.

: What happened to PERl 5.6 ? It seems that the only ActiveState version
: available is 5.6.35 which is multi-threaded ??? This prevents me from
: re-installing DBD::Pg (Pg wants a "non-threaded" version of Perl...)

Perl 5.6.35 is a variant of 5.6.

: Can anyone tell me where I can get a "non-threaded" Perl 5.6.x distribution
: ???

That's a better question!  =)

You can get pretty much all the old versions of ActiveState Perl off of
their FTP site.  Use th good old command-line ftp client (yes, Windows
has one) and go get it.

Or, use a browser:
	ftp://ftp.activestate.com/ActivePerl/Windows/5.6/

Hope that helps.

-- 
Louis Erickson - wwonko@rdwarf.com - http://www.rdwarf.com/~wwonko/

"Never underestimate the power of a small tactical nuclear weapon."


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

Date: Wed, 27 Aug 2003 16:15:31 +0000 (UTC)
From: Louis Erickson <wwonko@rdwarf.com>
Subject: Re: Perl Debugger, Windows NT and BSODs
Message-Id: <biilf3$31u$1@holly.rdwarf.com>

Bohne <simjesse@aol.com> wrote:
: I can't believe it!
: Doesn't ANYbody else have this problem?

From the responses you got when you asked this question last time, I suspect
that people aren't.

: Why me?

I would have to suspect that it's a system configuration issue.

<trimmed URL to be not horribly long>

http://groups.google.com/groups?th=8e103eafbee6cba7

: Recently I don't even get bluescreens any more, just a black screen as
: soon as I enter the debugger!

The Perl debugger isn't a very complicated (relatively speaking) program.
It's a console mode application.  It doesn't do anything wierd with DirectX,
graphics, sound, video, etc.  It uses standard methods to talk to the user.
It starts and stops it's own internal interpeter, which isn't magic.

The NT4 machine we have here works fine.

: It's driving me nuts!

I can understand how it would be.

Does it happen on every machine you've tried?  Have you considered completely
rebuilding the machine?

Were it a more complex program, I'd suggest bad memory that isn't getting
used until the extra modules were loaded, or a bad CPU that is causing
problems with the debug tools.  I'm confident that Perl doesn't use those
features of the OS - they'd be hard to do under Unix, where Perl began.

So, I fear you're alone.  You have much sympathy, but I doubt you'll find
an easy answer in the newsgroup.  If you do figure it out, please let us
(and the archives) know.

Sorry nobody knew what's wrong.  That happens sometimes.  Sometimes you're
the first one to fnd a problem.

-- 
Louis Erickson - wwonko@rdwarf.com - http://www.rdwarf.com/~wwonko/

If you live to the age of a hundred you have it made because very few
people die past the age of a hundred.  -- George Burns


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

Date: Mon, 1 Sep 2003 05:08:29 +0000 (UTC)
From: Louis Erickson <wwonko@rdwarf.com>
Subject: Problem with Date::Manip, taint mode, and CGI::Carp.
Message-Id: <biuk8d$89q$1@holly.rdwarf.com>


Hi, everyone.  I'm entering the wonderful world of "taint mode" and having
several interesting sorts of problems with it.  Most of them are pretty
straightforward and I can get around them.

I've found a problem, though, that I can't get around, and it's an odd one.

I use Date::Manip.  It's a favorite of mine, and fast enough for what I'm
doing.  I also use CGI::Carp.

In taint mode, those two don't work together.

I have to use 'BEGIN' to load Date::Manip, so there's a chance to clean up
PATH to something sensible.  I'd found it, and one of the articles on
Randal L. Schwartz's website
(http://www.stonehenge.com/merlyn/WebTechniques/col66.html) verified for
me that this was needed.  (Thanks very much, Randal!)

However, one of my CGI scripts wouldn't work, and I'm stumped as to why.
Apparently CGI::Carp('fatalsToBrowser') breaks Date::Manip's check to see
if we're in Taint mode.

If I have a script:

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

# Uncomment this to break the script.
#use CGI::Carp('fatalsToBrowser');

BEGIN {
$ENV{PATH}='/bin:/usr/bin';
require Date::Manip;
Date::Manip->import();
Date::Manip::Date_Init("Internal=1");
}

__END__

Anyone have any idea why, or what's to be done about this?  I can copy and
paste the line in Date::Manip that breaks in to my own script, and it works
fine; it's only a problem in Date::Manip.

Any suggestions or ideas would be very welcome!

Thank you all very much!

-- 
Louis Erickson - wwonko@rdwarf.com - http://www.rdwarf.com/~wwonko/

There are people so addicted to exaggeration that they can't tell the
truth without lying.


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

Date: Tue, 02 Sep 2003 19:22:19 GMT
From: "John W. Krahn" <krahnj@acm.org>
Subject: Re: Reading a scalar line by line
Message-Id: <3F54EDD8.A6995CD8@acm.org>

Tore Aursand wrote:
> 
> Why do you keep separate lines in a scalar anyway?  I find it handier to
> keep them in a list.

You can't KEEP anything in a list.  Perhaps you meant an array?  :-)

perldoc -q "What is the difference between a list and an array"



John
-- 
use Perl;
program
fulfillment


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

Date: Tue, 02 Sep 2003 19:17:30 GMT
From: "John W. Krahn" <krahnj@acm.org>
Subject: Re: Replacing IP's in ./etc/hosts
Message-Id: <3F54ECB7.E95354BF@acm.org>

Alex wrote:
> 
> I tried running your version of the script as:
> 
> #!/usr/bin/perl -w
> use strict;
> use Socket;
> 
> my ( $ip ) = `ifconfig hme0` =~ /inet addr:\s*(\S+)/;
> 
> my $ip_hostfile = do {
>     my @temp;
>     while ( @temp = gethostent ) { $temp[0] =~ /Morphine/ and last }
>     inet_ntoa $temp[-1];
>     };
> 
> if ( $ip eq $ip_hostfile ) {
>     print "The ip's are the same.  No changes made.\n";
>     exit 0;
>     }
> 
> print "The ip's are different, writing new ip to /etc/hosts\n";
> 
> ( $^I, @ARGV ) = ( '.back', '/etc/hosts' );
> 
> while ( <> ) {
>     s/^\Q$ip_hostfile\E\b/$ip/;
>     print;
>     }
> 
> And got the following errors:
> 
> Use of uninitialized value at ./ngscript line 13.
> The ip's are different, writing new ip to /etc/hosts
> Use of uninitialized value at ./ngscript line 23, <> chunk 5.
> 
> Any thoughts?

It looks like either $ip or $ip_hostfile contains the value undef.  Is
the regular expression /inet addr:\s*(\S+)/ valid for your version of
ifconfig?  Is the interface hme0 up and running?  You should probably
put in some safety checks to ensure valid data before trying to change
/etc/hosts.


my ( $ip ) = `ifconfig hme0` =~ /inet addr:\s*(\d+\.\d+\.\d+\.\d+)/
    or die "Invalid data from ifconfig hme0\n";


Also if /etc/hosts contains more than one line with the string
'Morphine' you may be changing the wrong line, for example:

0  # /etc/hosts file
1  # comment
2  #4.3.2.1    Morphine.org
3  5.4.3.2    one.Morphine.org    Morphine1
4  5.4.3.3    two.Morphine.org    Morphine

Line 2 will be skipped because it is a comment and line 3 will be
modified because it is the first host name that matches the regular
expression /Morphine/.  If the string 'Morphine' only occures once in
the /etc/hosts file then you will change the correct entry otherwise you
may have to test for an exact match and you may want to test against the
alias field of gethostent() as well ($temp[1] in the code above.)



John
-- 
use Perl;
program
fulfillment


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

Date: Tue, 02 Sep 2003 14:32:43 -0400
From: Shawn Corey <shawn@magma.ca>
Subject: Re: Silly push tricks
Message-Id: <Bnudneuilre3f8miXTWJkA@magma.ca>

Bill Smith wrote:

> "Shawn Corey" <shawn@magma.ca> wrote in message
> news:3l6dnaqT0_d6OsmiU-KYvg@magma.ca...
> --snip--
> 
>>map{&test($_)?push@sheep,$_:push@goats,$_}@bleats;
>>
> 
> I think that it is poor style to use 'map' when the return value is not
> used.  Use 'foreach' instead.  My extra parens may not be necessary, but
> I do not trust my memory of precedence rules.
> 
> Bill
> 
> &test($_)?push(@sheep,$_):push(@goats,$_) foreach @bleats;
> 
> 
That's like saying all subroutines must return a value. Perl, more than 
one way to do things.



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

Date: Tue, 02 Sep 2003 20:57:09 +0200
From: Tore Aursand <tore@aursand.no>
Subject: Re: Silly push tricks
Message-Id: <dK55b.26326$Hb.410369@news4.e.nsc.no>

Shawn Corey wrote:
>>> map{&test($_)?push@sheep,$_:push@goats,$_}@bleats;

>> I think that it is poor style to use 'map' when the return value is not
>> used.  Use 'foreach' instead.  My extra parens may not be necessary, but
>> I do not trust my memory of precedence rules.

> That's like saying all subroutines must return a value.

No, it's not.  Consider the following statement from 'perldoc';

   What's wrong with using grep or map in a void context?

   The problem is that both grep and map build a return list,
   regardless of the context.  This means you're making Perl go to
   the trouble of building a list that you then just throw away.
   If the list is large, you waste both time and space.  If your
   intent is to iterate over the list then use a for loop for this
   purpose.

> Perl, more than one way to do things.

Sure, but that doesn't mena you shouldn't follow good practices.


-- 
Tore Aursand <tore@extend.no>

"Whenever I see an old lady slip and fall on a wet sidewalk, my first
  instinct is to laugh. But then I think, what if I was an ant, and she
  fell on me. Then it wouldn't seem quite so funny." -- Jack Handey



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

Date: Tue, 02 Sep 2003 22:36:08 +0400
From: ddtl <this.is.invalid@yahoo.com>
Subject: Why qr// needs /o modifier, or bug in a documentation.
Message-Id: <kbo9lvg9vlbg1c12s9fia78kg8q3imjj0s@4ax.com>


Hello everybody,

I have some difficulty to understand why does qr// operator needs 
'o' modifier. There seems to be a disagreement between perlop manpage
and "Programming Perl" (3rd edition - i will use PP for short from now 
on).

From PP (chapter 5.9.2.2), it is clear that qr// needed for the cases
when it is impossible to use usual /o modifier, and a programmer wants
to spare recompilation every time RE is evaluated. Here is a quote:

-----------------------------------------------------------------------
Variables that interpolate into patterns necessarily do so at run time, 
not compile time. This slows down execution because Perl has to check 
whether you've changed the contents of the variable; if so, it would 
have to recompile the regular expression. As mentioned in 
"Pattern-Matching Operators", if you promise never to change the pattern, 
you can use the /o option to interpolate and compile only once:

print if /$pattern/o;

Although that works fine in our pgrep program, in the general case, 
it doesn't. Imagine you have a slew of patterns, and you want to match 
each of them in a loop, perhaps like this:

foreach $item (@data) {
    foreach $pat (@patterns) {
        if ($item =~ /$pat/) { ... }
    }
}

You couldn't write /$pat/o because the meaning of $pat varies each time 
through the inner loop.

The solution to this is the qr/PATTERN/imosx operator. This operator 
quotes--and compiles--its PATTERN as a regular expression. PATTERN is 
interpolated the same way as in m/PATTERN/. If ' is used as the delimiter,
no interpolation of variables (or the six translation escapes) is done. 
The operator returns a Perl value that may be used instead of the equivalent 
literal in a corresponding pattern match or substitute.
-----------------------------------------------------------------------

But perlop manpage says something different:


-----------------------------------------------------------------------
qr/STRING/imosx

    This operator quotes (and possibly compiles) its STRING as a regular 
    expression. STRING is interpolated the same way as PATTERN in m/PATTERN/. 
    If "'" is used as the delimiter, no interpolation is done. Returns a 
    Perl value which may be used instead of the corresponding /STRING/imosx 
    expression. 
-----------------------------------------------------------------------

According to the manpage, it is quite common that qr//  does not compile
RE, which is, except being different from the said in the book, doesn't
really make sense - why would otherwise anybody will need qr// for?

Also, the book doesn't even mention an existence of /o modifier for
qr// when he talks about modifiers (in the same section. though it
does mention it in the previous quote):

-----------------------------------------------------------------------
 ...
 ...
The reason this works is because the qr// operator returns a special kind 
of object that has a stringification overload as described in Chapter 13, 
"Overloading". If you print out the return value, you'll see the equivalent
string:

$re = qr/my.STRING/is;
print $re;                  # prints (?si-xm:my.STRING)

The /s and /i modifiers were enabled in the pattern because they were 
supplied to qr//. The /x and /m, however, are disabled because they were not.
-----------------------------------------------------------------------



Additionally, using "use re "debug";" option, i checked what is the 
difference between when you add /o modifier to qr// and when you don't - 
and as i found out - there is no difference, the expression was compiled 
only once when compiler reached qr// operator (while it was compiled every
time RE was evaluated when a usual double-quoted string was used. 
Here is my test case:

---------------------------------------
#!/usr/bin/perl
use strict;
use re "debug";

my $re = qr/world/;
"hello world" =~ /$re/;  
"hello world" =~ /$re/;
---------------------------------------


The output i get when running the program (which is the same regardless of
/o modifier)



---------------------------------------
Compiling REx `world'
size 4 Got 36 bytes for offset annotations.
first at 1
   1: EXACT <world>(4)
   4: END(0)
anchored `world' at 0 (checking anchored isall) minlen 5 
Offsets: [4]
        1[5] 0[0] 0[0] 6[0] 
Guessing start of match, REx `world' against `hello world'...
Found anchored substr `world' at offset 6...
Starting position does not contradict /^/m...
Guessed: match at offset 6
Guessing start of match, REx `world' against `hello world'...
Found anchored substr `world' at offset 6...
Starting position does not contradict /^/m...
Guessed: match at offset 6
Freeing REx: `"world"'
---------------------------------------




Is there is an error in the manpage? If it is not, how it is possible to 
explain the difference between the book and the manpage, and especially - 
why there is a need for qr// according to the manpage's version?


ddtl.




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

Date: Tue, 02 Sep 2003 18:36:40 GMT
From: "John W. Krahn" <krahnj@acm.org>
Subject: Re: write hex to socket, weird
Message-Id: <3F54E326.8EE469D7@acm.org>

c|sc0 wrote:
> 
> I just want to write raw data to a socket (by using IO::Socket)
> All I want to do is the following:
> 
> print $my_socket "\x0f\xa1\x02.....and much more here";
> 
> A part of the data is actually an IP address
> so in my case if I want to send "10.1.2.3" I should send "\x0a\01\x02\x3"
> 
> I tried to create a sub() to generate the "\x0a\01\x02\x3" out of
> "10.1.2.3", but I failed.

Use inet_aton() from the modules Socket or IO::Socket.

perldoc Socket


> Obviously the following does not work:
> 
> $code .= "\\x" . substr( unpack("H*", pack("N*", $my_byte)) , -2 ,2);
> 
> I tried many more ways but still can't achieve it.
> I'd like to do such a sub() for "string" as well
> 
> e.g "ABC"  should give "\x41\x42\x43"
> but as you already understood, i dont want the string "\x41\x42\x43" but
> the actually value behind it.

"ABC" and "\x41\x42\x43" contain exactly the same data:

$ perl -le'print "\x41\x42\x43"'
ABC
$ perl -le'$x = "\x41\x42\x43"; $y = "ABC"; print "True" if $x eq $y'
True


If you need to expand "ABC" to "\x41\x42\x43":

$ perl -le'$x = q(ABC); $x =~ s/(.)/ sprintf q(\x%x), ord $1 /ges; print
$x'
\x41\x42\x43



John
-- 
use Perl;
program
fulfillment


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

Date: Sat, 19 Jul 2003 01:59:56 GMT
From: Bob Walton <bwalton@rochester.rr.com>
Subject: Re: 
Message-Id: <3F18A600.3040306@rochester.rr.com>

Ron wrote:

> Tried this code get a server 500 error.
> 
> Anyone know what's wrong with it?
> 
> if $DayName eq "Select a Day" or $RouteName eq "Select A Route") {

(---^


>     dienice("Please use the back button on your browser to fill out the Day
> & Route fields.");
> }
 ...
> Ron

 ...
-- 
Bob Walton



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

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


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