[22492] in Perl-Users-Digest

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

Perl-Users Digest, Issue: 4713 Volume: 10

daemon@ATHENA.MIT.EDU (Perl-Users Digest)
Sat Mar 15 14:05:44 2003

Date: Sat, 15 Mar 2003 11:05:08 -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           Sat, 15 Mar 2003     Volume: 10 Number: 4713

Today's topics:
    Re: [Probably] a stupid question about REGEX (Mark Healey)
    Re: CPAN.pm: version of installed module not updated? <slaven@rezic.de>
    Re: file parse into hash and writing output with certai (Anno Siegel)
    Re: FILEHANDLE and search and replace question (Jay Tilton)
    Re: FILEHANDLE and search and replace question <REMOVEsdnCAPS@comcast.net>
    Re: FILEHANDLE and search and replace question <NoSpamPleaseButThisIsValid2@gmx.net>
    Re: FILEHANDLE and search and replace question <jurgenex@hotmail.com>
    Re: FILEHANDLE and search and replace question <garry@ifr.zvolve.net>
    Re: FILEHANDLE and search and replace question (Anno Siegel)
    Re: Getting list of files from Win32 clipboard (Jay Tilton)
    Re: how to create NULL character in perl (Jay Tilton)
        How to find a word which is palindromica using REGEXP <qin@freebsd.lzu.edu.cn>
    Re: How to find a word which is palindromica using REGE <jurgenex@hotmail.com>
    Re: How to find a word which is palindromica using REGE <garry@ifr.zvolve.net>
    Re: map - sort - lc in one statement (Anno Siegel)
    Re: my $x = 100 for 1..3  why is $x undef (Anno Siegel)
    Re: my $x = 100 for 1..3  why is $x undef (Jay Tilton)
    Re: Stupid Perl Questions <wsegrave@mindspring.com>
    Re: Stupid Perl Questions <wsegrave@mindspring.com>
        Digest Administrivia (Last modified: 6 Apr 01) (Perl-Users-Digest Admin)

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

Date: 15 Mar 2003 12:28:04 -0600
From: die@spammer.die (Mark Healey)
Subject: Re: [Probably] a stupid question about REGEX
Message-Id: <VP2SpNyJrzMZ-pn2-FpMwYkXc8xdZ@adsl-63-207-135-60.dsl.sndg02.pacbell.net>

On Sat, 15 Mar 2003 08:49:57 UTC, Uri Guttman <uri@stemsystems.com> 
wrote:

> >>>>> "MH" == Mark Healey <die@spammer.die> writes:
>
>   MH> For the life of me I can't figure out how to do a regex comparison
>   MH> between $_ and $anyVariable.
>
>   MH> You can see my attempt on line 54.  I've tried $last =~ /$_/i as well
>   MH> with no results.
>
>   MH> I'm probably missing something simple but can't seem to find it.
>
>
>   MH>      48       foreach(@lines)
>   MH>      49          {
>   MH>      50          if (/\A">/)
>   MH>      51             {
>   MH>      52             foreach(@searchTerms)
>   MH>      53                {
>   MH>      54                if (/$_/i =~ $last)
>
> i am surprised no one else has mentioned you have those arguments
> backwards. that is being parsed as /$_/i by itself and the result of
> that (a boolean) being compared to the regex in $last.
>
> it should be
>
>                 if ( $last =~ /$_/i )
>
> you claim you tried that but there is no way the current line makes
> sense. now if you change it back to this and show some data and regexes
> then the real bug could be found.

All I want to do is determine if $_ is a substring of $last, ignoring
case.

For example I submitted "mission hills" to the website and got these
three responses.  It is an ORed keyword search which gives me the
false positive third line because it contains "hills".  I'd like to
filter the false positives.


MISSION HILLS Sat 8-12. Multi-fam. Fun items, good prices. 3760 Hawk 
St. off University btween Sutter & Bush

MISSION HILLS Moving sale Sat-Sun 9-5. Furniture, clothing, pictures &
more. 4126 ARDEN WAY

MOUNT HELIX, Sat 7-1. Multi-Family. Rolling Hills/ Sunrise Hills. 
Furn, appls, toys, antiques, clothes, misc







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

Date: 15 Mar 2003 18:11:00 +0100
From: Slaven Rezic <slaven@rezic.de>
Subject: Re: CPAN.pm: version of installed module not updated?
Message-Id: <87isuk7dy3.fsf@vran.herceg.de>

"Frank Maas" <spamfilter@cheiron-it.nl> writes:

> Hi,
> 
> I try to keep up with new versions of installed modules by using the 'r'
> function in the CPAN shell. However, it seems that this list cannot be
> trusted. The list tells me (for instance) that I have GD::Polyline version
> 0.1 and 0.2 is available. So I 'install GD::Polyline'. Firstly it looks
> as if it does not get installed, but after a manual 'make install' it
> does. 'r' is still showing '0.1' as active version though.

This is because there's still the old version lying around in the
architecture-dependent site_perl directory (on my system:
/usr/perl5.8.0/lib/site_perl/5.8.0/i386-freebsd-64int/GD/Polyline.pm)
while the new one is in the architecture-independent site_perl
directory (on my system:
/usr/perl5.8.0/lib/site_perl/5.8.0/GD/Polyline.pm).

> 
> Now I suspect it's something in the module install script, but it happens
> a lot (Pod::Parser, XML::LibXML::Iterator, even Net::Cmd). Any ideas about
> this?
>
> While at the subject: is there a simple 'update' command/module/whatever?
> So that in stead of 'while ('r'->list) { install 'r'->list->first; }' by
> hand it is somewhat automated (eg. RedHat's up2date)?
> 

First use autobundle, then install the generated Bundle.

Regards,
	Slaven

-- 
Slaven Rezic - slaven@rezic.de

    tkruler - Perl/Tk program for measuring screen distances
    http://ptktools.sourceforge.net/#tkruler


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

Date: 15 Mar 2003 17:49:18 GMT
From: anno4000@lublin.zrz.tu-berlin.de (Anno Siegel)
Subject: Re: file parse into hash and writing output with certain format to new file
Message-Id: <b4vp2u$s2o$1@mamenchi.zrz.TU-Berlin.DE>

david <dwlepage@yahoo.com> wrote in comp.lang.perl.misc:
> I am new to perl as im sure my code will show, which is partly the
> reason for this post. What im trying to do a replace a one field in a
> file with another, write a second file with this modification, store
> these two fields in a hash, and use them to populate data into a 3rd
> file.
> Here is what I have so far, which works, but im sure could use
> improvements.
> 
> #!/usr/bin/perl 
> use strict;

"use strict" is fine, but where is "use warnings"?  If you're not sure
about the quality of your code, one of the first things is to look for
warnings it may produce.  These are often a sign that something works
for the wrong reason.

> my @seperate = ();
> my %records;
> my ($fields, $ser, $key, $value);

No need (and not good) to declare these here.  They are used only
in the loop, where you correctly declare them.

> open (FILE, "<import0.dat") || die "Couldn't open file; $!\n";
> open (OUT, ">output.dat") || die "Couldn't create file; $!\n";
> open (NEWOUT, ">newout.dat") || die "Couldn't create; $!\n";
> 
> while ( <FILE> ) {
>         my @fields = split ( /\Q,\E/ );

"," isn't special in a regex, you don't need \Q and \E.

>         if ( $fields[7] =~ m/^(\$\$)(S\/N:)(\w+)/ ) {

This can be simplified.  The first two parentheses capture fixed strings,
which is unnecessary.  $2 is not used anyway.

>                 my @ser = "$1$3$1";

Why is @ser an array?  You only ever store a single scalar in it.

>                 ( $fields[1], $ser[0] ) = ( $ser[0], $fields[1] );

Make the last three lines

    if ( $fields[7] =~ m{^\$\$S/N:(\w+)} ) {
        my $ser = '$$' . $1;
        ( $fields[1], $ser ) = ( $ser, $fields[1] );

>                 push ( @seperate, join (',', @fields) );
>         $records{"@ser"} = $fields[1];

Weird indentation.  The last line becomes

    $records{$ser} = $fields[1];

>                 foreach my $records (keys %records) {                 
>               
>                      }

The "foreach" loop does nothing.  Throw it out.

>         }
> 
> #while ( ($key,$value ) = each %records ) {
> #        print OUT "$key --> $value\n";
> 
> }
> print OUT "@seperate\n";
> close(FILE);
> close (OUT);
> close (NEWOUT);
> 
> Is there a better way to do this?

Not fundamentally.  Many details could be improved.

> My second question is once I have these values in the hash table what
> is the best way to use these values to populate a third file?
> For example, I want to create a third file (sent to "NEWOUT") which
> has the format:
> 
> User = $fields[1]
> Number = @ser
> 
> User = $fields[1]
> Number = @ser

Then write them as soon as you have the data.  Add

    print NEWOUT "User = $fields[1]\n";
    print NEWOUT " Number = @ser\n";

to the loop body.  I don't see the need for the hash from what you have now.

Anno


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

Date: Sat, 15 Mar 2003 15:31:23 GMT
From: tiltonj@erols.com (Jay Tilton)
Subject: Re: FILEHANDLE and search and replace question
Message-Id: <3e7346af.28708562@news.erols.com>

Marek Stepanek <mstep@t-online.de> wrote:

: And in fact I doubted about it: you need a second (!!!) file to replace
: something in the original, which gives me three files to have an result in
: html: first file, comma separated Database-file resulting from a huge
: perl-program, second the results in a big table in an temporarily html-file,
: and a third one to change some tiny little html in it :-(

Why the intermediate step of writing a file that needs changing?  Is
there a reason you cannot create the html document correctly the first
time?



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

Date: Sat, 15 Mar 2003 09:53:49 -0600
From: "Eric J. Roode" <REMOVEsdnCAPS@comcast.net>
Subject: Re: FILEHANDLE and search and replace question
Message-Id: <Xns933F6EE366905sdn.comcast@216.166.71.239>

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

Marek Stepanek <mstep@t-online.de> wrote in
news:BA98E881.4D36%mstep@t-online.de: 

> <provocation>
> And in fact I doubted about it: you need a second (!!!) file to
> replace something in the original, which gives me three files to
have
> an result in html: first file, comma separated Database-file
resulting
> from a huge perl-program, second the results in a big table in an
> temporarily html-file, and a third one to change some tiny little
html
> in it :-( 

That's nothing to do with Perl (or C, or Unix, or Java, or...);
that's computer science.

 
> I have nearly every Perl-Book meanwhile, but nobody is telling us
> newbies that s///g is not working "in place" on one file.

Gosh, I've read many books on Perl from cover to cover, and I don't
recall *any* of them indicating that s//g works in-place on a file. 
s//g works on a variable (duh?). 

You may as well complain that none of your Perl books told you that
s//g won't prove Fermat's Last Theorem.

> Why is it
> not possible to read in a file treat the content, and write the
> changed text back to the same file??? Or probably I oversaw a
footnote
> ??? Or probably I did not understand how to do it elegantly.
> Astonishing that Perl is said to be a powerful language to treat
text
> files ... 

Did you notice the parts about the -i and -p command-line options?

- -- 
Eric
print scalar reverse sort qw p ekca lre reh 
ts uJ p, $/.r, map $_.$", qw e p h tona e;

-----BEGIN xxx SIGNATURE-----
Version: GnuPG v1.2.1 (MingW32) - WinPT 0.5.13

iD8DBQE+c0yQY96i4h5M0egRAvGsAKCvRhkgrkQjQZfo8IPTOrXaQ6mxLwCgqHvu
Ek35EQgKyyXfVJHLPN1l36E=
=sNow
-----END PGP SIGNATURE-----


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

Date: Sat, 15 Mar 2003 17:16:04 +0100
From: Wolf Behrenhoff <NoSpamPleaseButThisIsValid2@gmx.net>
Subject: Re: FILEHANDLE and search and replace question
Message-Id: <3E7351C4.5CEA4708@gmx.net>

Marek Stepanek wrote:
> 
> <provocation>
> And in fact I doubted about it: you need a second (!!!) file to replace
> something in the original, which gives me three files to have an result in
> html: first file, comma separated Database-file resulting from a huge
> perl-program, second the results in a big table in an temporarily html-file,
> and a third one to change some tiny little html in it :-(

You don't need a 2nd file. Cosider this:

open(FILE, '<myFile'); my @lines=<FILE>; close FILE;
s/search/replace/ for @lines;
open(FILE, '>myFile'); print FILE @lines; close FILE;

But I think it is safer to have a second file:
- you can work with single lines and don't need to keep everything in
RAM
- if your computer chrashes while writing you might have data loss.

> I have nearly every Perl-Book meanwhile,

so you are very rich :-)

> but nobody is telling us newbies
> that s///g is not working "in place" on one file.

Read the documentation! -> perldoc perlop

s/PATTERN/REPLACEMENT/egimosx
        Searches a string for a pattern, and if found, replaces that
        pattern with the replacement text and returns the number of
        substitutions made. Otherwise it returns false (specifically,
        the empty string).

so
  $_='hello'; print s/l/x/g;
prints '2' not 'hexxo'

> Why is it not possible to
> read in a file treat the content, and write the changed text back to the
> same file??? Or probably I oversaw a footnote ??? Or probably I did not
> understand how to do it elegantly. 

It is possible. (see above or read perldoc -f seek/truncate)

Wolf



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

Date: Sat, 15 Mar 2003 16:18:28 GMT
From: "Jürgen Exner" <jurgenex@hotmail.com>
Subject: Re: FILEHANDLE and search and replace question
Message-Id: <onIca.12803$Ad6.771@nwrddc01.gnilink.net>

Marek Stepanek wrote:
> I have nearly every Perl-Book meanwhile, but nobody is telling us
> newbies that s///g is not working "in place" on one file.

You are aware of the difference between a programming language and a text
editor, are you?
See also "perldoc -q change":
      How do I change one line in a file/delete a line in a file/insert a
line in the middle of a file/append to the beginning of a file?

> Why is it
> not possible to read in a file treat the content, and write the
> changed text back to the same file???

That's actually trivial:

open FOO, "bar" or die "Can't open bar because $!\n";
my @filecontent = <FOO>;
close FOO;
#now mangle the file content as you please
open FOO, ">bar" or die "Can't open bar for writing because $!\n";
print FOO @filecontent;
close FOO;

> Astonishing that Perl is said to be a powerful language to treat text
> files ... </provocation>

It is a powerful language to treat text.
Files are handled by the OS, not by a programming language.

jue




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

Date: Sat, 15 Mar 2003 17:40:04 -0000
From: Garry Williams <garry@ifr.zvolve.net>
Subject: Re: FILEHANDLE and search and replace question
Message-Id: <slrnb76pbj.b10.garry@zfw.zvolve.net>

On Sat, 15 Mar 2003 10:19:42 +0100, Marek Stepanek <mstep@t-online.de>
wrote:

> I am new to perl and have a question about a search and replace,
> which is not working in my script.

Your problem is not "search and replace".  

[snip]

> for (@alle_zeilen=<GLOBALRESULT_HTM>) {
>     print GLOBALRESULT_HTM s/ohne|mit/<SPAN CLASS=\"wichtig\">$&<SPAN>/g;
>     }
> 
> but it is not working :-( I feel I am missing something obviously.

"not working" doesn't help very much.  

But your question is a FAQ: 

  perldoc -q change

    "How do I change one line in a file/delete a line in a
     file/insert a line in the middle of a file/append to the
     beginning of a file?"

-- 
Garry Williams


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

Date: 15 Mar 2003 18:27:44 GMT
From: anno4000@lublin.zrz.tu-berlin.de (Anno Siegel)
Subject: Re: FILEHANDLE and search and replace question
Message-Id: <b4vrb0$6r$1@mamenchi.zrz.TU-Berlin.DE>

Marek Stepanek  <mstep@t-online.de> wrote in comp.lang.perl.misc:
> On 15.03.2003 10:41 Uhr, in article
> b0t57v885t7b0rjq489pn56gk4v0u0k3ig@4ax.com, "Bart Lateur"
> <bart.lateur@pandora.be> wrote:
> > Marek Stepanek wrote:
> > 
> >> How do I open the file correctly (with < or > or +< or +>) to make a search
> >> and replace?

[...]

> Thanx Bart,
> 
> Inspired from your answer, I found _my_ solution, after two weeks of
> desperate search. 
> 
> Two mistakes: 
> 
> for (<GLOBALRESULT_BAK_HTM>) {
>     print GLOBALRESULT_HTM s/ohne|mit/<SPAN CLASS=\"wichtig\">$&<SPAN>/g;
>     }
> 
> should be: 
> 
> for (<GLOBALRESULT_BAK_HTM>) {
>     s/ohne|mit/<SPAN CLASS=\"wichtig\">$&<SPAN>/g;
>     print GLOBALRESULT_HTM;
>     }
> 
> 
> <provocation>
> And in fact I doubted about it: you need a second (!!!) file to replace
> something in the original, which gives me three files to have an result in
> html: first file, comma separated Database-file resulting from a huge
> perl-program, second the results in a big table in an temporarily html-file,
> and a third one to change some tiny little html in it :-(

As Bart has explained, it is possible to avoid the "extra" file.  You
open the original r/w, read it, make changes, rewind it and rewrite it.
Works just fine, but it comes at a risk because there's a time when the
file content is only in memory (and not on disk).  That's why it's
rarely done.

> I have nearly every Perl-Book meanwhile, but nobody is telling us newbies
> that s///g is not working "in place" on one file.

Nothing in the documentation even hints that it does.  When you read
data from a file, there is no magical link that connects the variable
with the data on disk.  What you get is just a copy, a snapshot really.

>                                                   Why is it not possible to
> read in a file treat the content, and write the changed text back to the
> same file???

Oh, it is possible, with the help of the right module(s).  You can
magically tie a variable to a line in a file, and indeed an array
to an entire file, so that every change in a variable is reflected
on disk.  See the Tie::File module (standard in 5.8.0).  With an
earlier Perl, see the FAQ "perldoc -q 'line in a file'" for a discussion
of other options.

>              Or probably I oversaw a footnote ??? Or probably I did not
> understand how to do it elegantly. Astonishing that Perl is said to be a
> powerful language to treat text files ...

Your misunderstanding is by no means specific to Perl.  Beginners have
this problem in any language where files are opened before use.

Anno


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

Date: Sat, 15 Mar 2003 14:21:28 GMT
From: tiltonj@erols.com (Jay Tilton)
Subject: Re: Getting list of files from Win32 clipboard
Message-Id: <3e7335b0.24356457@news.erols.com>

Gunnar Hjalmarsson <noreply@gunnar.cc> wrote:
: Jay Tilton wrote:
: > Gunnar Hjalmarsson <noreply@gunnar.cc> wrote:
: > : >   $CLIP->Set($CLIP->GetText);
: > : 
: > : What's the point with that? As far as I understand, it just pastes the 
: > : very same text string to the clipboard as was just copied from the 
: > : clipboard...
: > 
: > Eh.  Not really the same.  What is on the clipboard is a set of file
: > objects, which is more than just a text string of filenames.
: 
: That question refers only to the
: 
:      $CLIP->Set($CLIP->GetText);
: 
: statement, which seems to be executed only when the clipboard does *not* 
: contain files.

I misread the comment.  Yes, that part does seem a bit of a no-op.



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

Date: Sat, 15 Mar 2003 15:47:16 GMT
From: tiltonj@erols.com (Jay Tilton)
Subject: Re: how to create NULL character in perl
Message-Id: <3e734943.29368087@news.erols.com>

"news.pacific.net.sg" <xiamen2@hotmail.com> wrote:

: I'm trying to get a NULL character in perl.
: 
: my $null = Win32::OLE::Variant->new(VT_NULL,undef);
: 
: This doesn't work

That works fine for me.  Whatever's wrong with it is not obvious.

: and cause me memory error,

What does that mean?  Is an error message being generated by perl or
by the OS?



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

Date: 15 Mar 2003 23:08:11 +0800
From: qin jiang wei <qin@freebsd.lzu.edu.cn>
Subject: How to find a word which is palindromica using REGEXP
Message-Id: <863clo1xd0.fsf@freebsd.lzu.edu.cn>


How can I find the palindromica words in /usr/share/dict/words
For example , the word 'level'.





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

Date: Sat, 15 Mar 2003 15:23:52 GMT
From: "Jürgen Exner" <jurgenex@hotmail.com>
Subject: Re: How to find a word which is palindromica using REGEXP
Message-Id: <cAHca.12757$Ad6.5873@nwrddc01.gnilink.net>

qin jiang wei wrote:
> How can I find the palindromica words in /usr/share/dict/words
> For example , the word 'level'.

Please see http://www.badtz.org/pics/bart.gif, this has been discussed in
depth many times, including a Perl golf contest.

jue




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

Date: Sat, 15 Mar 2003 18:51:08 -0000
From: Garry Williams <garry@ifr.zvolve.net>
Subject: Re: How to find a word which is palindromica using REGEXP
Message-Id: <slrnb76tgo.b10.garry@zfw.zvolve.net>

On 15 Mar 2003 23:08:11 +0800, qin jiang wei <qin@freebsd.lzu.edu.cn>
wrote:

> How can I find the palindromica words in /usr/share/dict/words
> For example , the word 'level'.

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

    my $half = (length() - 1) / 2;

    my $re   = '(.)' x $half;

    $re .= '.' if length % 2;

    $re .= join '', map "\\$_", reverse 1 .. $half;

    print if /^$re$/;

-- 
Garry Williams


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

Date: 15 Mar 2003 17:06:57 GMT
From: anno4000@lublin.zrz.tu-berlin.de (Anno Siegel)
Subject: Re: map - sort - lc in one statement
Message-Id: <b4vmjh$qjb$1@mamenchi.zrz.TU-Berlin.DE>

John W. Krahn <krahnj@acm.org> wrote in comp.lang.perl.misc:
> Peter Shankey wrote:
> > 
> > #!/bin/perl
> > 
> > #give data in the form of:
> > my @lines = qw(
> > aaa:bbb:Y
> > aaA:bbB:y
> > aAa:bBb:Y
> > aAA:bBB:y
> > ccc:ddd:y
> > ccC:ddD:y
> > cCc:dDd:Y
> > cCC:dDD:y
> > aaa:bbb:Y
> > aaA:bbB:y
> > aAa:bBb:Y
> > aAA:bBB:y
> > ccc:ddd:y
> > ccC:ddD:y
> > cCc:dDd:Y
> > cCC:dDD:y
> > );
> > 
> > # I want the second column (b's and d's) to be case sensitive on a sort and
> > the
> > # primary column in the sort. As in reality the second column is a unix
> > # directory path.
> > # The first column is not case sensitive. I want the entries ordered
> > # alpha-numeric. The first column is the secondary sort
> > 
> > # I found I could do this in 2 steps:
> > @lines = map { $_->[0] }
> >  sort {
> >   $a->[2] cmp $b->[2]
> >           ||
> >   lc($a->[1]) cmp lc($b->[1])
> >           ||
> >   lc($a->[3]) cmp lc($b->[3])
> >  }
> >  map { [ $_, (split /:/) ] }
> >  @lines;
> > 
> > @lines = map { join ':', lc($_->[0]), $_->[1], lc($_->[2]) }
> >  map { [ @_,@_,@_, (split /:/) ] }
> >  @lines;
> > 
> > foreach (@lines){
> >  print($_, "\n");
> > }
> > 
> > # I tied to combine the lines into one line but I could not get it to work
> > # Is there anyway to combine the two steps into one?
> 
> This looks loke the perfect place for a GRT.  This produces the same
> results as yours.
> 
> @lines = map join( ':', (split /:/)[1,0,2] ),
>          sort
>          grep s/^([^:]+):([^:]+):([^:]+)$/$2:\L$1:$3/,
>          @lines;
> 
> print "$_\n" for @lines;

Ah, a grep() syncopates the steady beat of map() in this thread.  I like
it.

It does a lot of things:  Isolate the fields, adjust case, and regroup
in sort order.  As a bonus, it ignores invalid input.  It's cute, perhaps
irresistibly so, but a maintainer might not appreciate it.

For a little load-leveling, one could consider the case-adjustment a
step of data-preparation and do it in a separate step.  This is
contrary to the OPs intention, but a little clearer, imo:

    do { s/^([^:]+:)/\L$1/; s/(:[^:]+)$/\L$1/ } for @lines;
    
    @lines = map substr( $_, length()/2),
             sort
             map join( ':', (split ':')[ 1, 0, 2]) . $_,
             @lines;

Anno


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

Date: 15 Mar 2003 15:10:06 GMT
From: anno4000@lublin.zrz.tu-berlin.de (Anno Siegel)
Subject: Re: my $x = 100 for 1..3  why is $x undef
Message-Id: <b4vfoe$mbs$1@mamenchi.zrz.TU-Berlin.DE>

Bernie Cosell  <bernie@fantasyfarm.com> wrote in comp.lang.perl.misc:
> Abigail <abigail@abigail.nl> wrote:
> 
> } Martien Verbruggen (mgjv@tradingpost.com.au) wrote on MMMCDLXXX September
> } MCMXCIII in <URL:news:slrnb6t9av.79p.mgjv@verbruggen.comdyn.com.au>:
> } ##  
> } ##  It is not a bug, because it is documented to result in undefined
> } ##  behaviour.
> } 
> } I'm not quite sure I agree with that. 
> } 
> } When people started trying this construct ('my $foo = 1 if 0;'), 
> } people argued whether that was a feature or not. ...
> 
> I was one such ... for those who weren't around for that, at least in some
> versions of perl [haven't tried it in 5.8] the construct:
>    my $foo = 1 if 0;
> gave you a cheap static lexical variable: $foo is defined lexically, but
> doesn't get anything assigned to it, and [as it turns out] it *retains* the
> last value it had.  And so if you write:
> 
> > perl -e 'sub a {my $x = 0 if 0;
>                   print "\$x is $x\n"; 
>                   $x= $_[0]};
>            a(1); a(2); a(3);'
> $x is
> $x is 1
> $x is 2
> 
> I thought that was pretty cool [especially since it is a mile cleaner and
> simpler (at least from the outside..:o)) than the 'official' way of getting
> a local-static-variable]... 

What do you consider the "official" way of creating a static variable?

Since we have closures, we can declare a lexical outside the sub and use
it inside.  To make it private, enclose the whole thing in a bare block.
So the standard implementation would be

    {
        my $x = 0;
        sub a {
            print "\$x is $x\n";
            $x = shift;
        }
    }
    a( $_) for 1 .. 3;

If it matters that $x is only set at run time, prefix the block with
"BEGIN".

How much cleaner can it get get?  As for simplicity, if you understand
lexical scoping, you understand what this construct does.  Perl has to
work pretty hard to make lexical scoping work with closures, but that's
not the programmer's concern.

> } ...Only after p5p
> } couldn't decide what to do with it, they decided to at least
> } document it as having undefined behaviour.
> 
> Interesting.  I didn't hear that.  What'd be neater than supporting this
> rather hacky usage, IMO, would be to take advantage of the way it actually
> works and enshrine it in a real 'static' declaration [which ought not take
> much work, since it already *functions* as a static --- all that's missing
> is an 'approved' connection to the existing behavior]

I don't think we need that, and I don't think we want that.  Perl already
has too many declarations and declaration-like statements which relate in
the most un-orthogonal ways.  We may have come to know and love this mess,
but adding a compile-time-only version of "my" under the name "static" to
it might not be a good idea.  Look what happened with filehandles... :)

I think the closure solution is far superior.  It extends trivially to
more than one routine sharing a set of variables.  This makes the whole
construct something like a classless anonymous object, if an object is
a set of data together with a set of routines that operate on the data.

Anno


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

Date: Sat, 15 Mar 2003 15:27:02 GMT
From: tiltonj@erols.com (Jay Tilton)
Subject: Re: my $x = 100 for 1..3  why is $x undef
Message-Id: <3e734231.27558608@news.erols.com>

Bernie Cosell <bernie@fantasyfarm.com> wrote:

: Abigail <abigail@abigail.nl> wrote:
: 
: } When people started trying this construct ('my $foo = 1 if 0;'), 
: } people argued whether that was a feature or not. ...
: 
: I was one such ... for those who weren't around for that, at least in some
: versions of perl [haven't tried it in 5.8] the construct:
:    my $foo = 1 if 0;
: gave you a cheap static lexical variable: $foo is defined lexically, but
: doesn't get anything assigned to it, and [as it turns out] it *retains* the
: last value it had.  And so if you write:
: 
: > perl -e 'sub a {my $x = 0 if 0;
:                   print "\$x is $x\n"; 
:                   $x= $_[0]};
:            a(1); a(2); a(3);'
: $x is
: $x is 1
: $x is 2
: 
: I thought that was pretty cool [especially since it is a mile cleaner and
: simpler (at least from the outside..:o)) than the 'official' way of getting
: a local-static-variable]... 

Yah, it's a neat trick, but things get complicated in recursive
circumstances.  Instead of getting a single static variable at all
depths of recursion, you get a different variable at each depth.

Maybe that could be a sub-feature, but there's no way would I want to
be responsible for adequately documenting it and ensuring consistency
in all future revisions of the language.



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

Date: Sat, 15 Mar 2003 10:51:19 -0600
From: "William Alexander Segraves" <wsegrave@mindspring.com>
Subject: Re: Stupid Perl Questions
Message-Id: <b4vlv6$ntl$1@slb9.atl.mindspring.net>

"Caesar_Ancheta" <caesar_ancheta@yahoo.com> wrote in message
news:5d34f091.0303150248.6b8ae652@posting.google.com...
> Although the answers were freely given, you may have enabled a crack
> attack. The most questionable technology is the TinyPerl,TinyWeb on a
> floppy. I suggest that one misuse of this thread would be to zip the
> above and take over a file system.

Hmmm. Since the top-poster is commenting on something I added (to the
thread), I'll respond.

IIRC, there was nothing in the OP's questions that suggested the OP's
computer would be connected to the Internet, or that there was any network
connection at all.

It's certainly fair for Mr. Ancheta to infer that TinyWeb might pose a
security risk, if the computer on which the TinyWeb server is running is
connected to a network. No such use was contemplated, AFAICT, by the OP, and
certainly not by me.

FWIW, the purpose for which I had put together TinyPerl for a perl
executable file and TinyWeb for a web server was to make it possible for a
user to employ a CGI server running as "localhost" or "127.0.0.1" *without*
installing any software or directories on the host computer. The fact that
the complete system fits on a floppy is coincidental. In fact, it runs a bit
faster, as well as with less noise, when I run the system from CompactFlash
media.

That said (written), as with any web server, anyone contemplating deploying
his own web server, even as "localhost" on a standalone computer, should
read the documentation for both TinyPerl and TinyWeb, if they are used,
before using them. IMO, there is little or no risk from outside attacks
associated with the usage I've stated, standalone computer, no Internet or
network connection, and TinyWeb running as "localhost" or "127.0.0.1".

So, Mr. Ancheta, what is it that is questionable about the use of TinyPerl
and TinyWeb in the context I've stated?

Cheers.

Bill Segraves




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

Date: Sat, 15 Mar 2003 11:18:44 -0600
From: "William Alexander Segraves" <wsegrave@mindspring.com>
Subject: Re: Stupid Perl Questions
Message-Id: <b4vnht$r6e$1@slb3.atl.mindspring.net>

"William Alexander Segraves" <wsegrave@mindspring.com> wrote in message
news:b4vlv6$ntl$1@slb9.atl.mindspring.net...
> "Caesar_Ancheta" <caesar_ancheta@yahoo.com> wrote in message
> news:5d34f091.0303150248.6b8ae652@posting.google.com...
> > Although the answers were freely given, you may have enabled a crack
> > attack. The most questionable technology is the TinyPerl,TinyWeb on a
> > floppy. I suggest that one misuse of this thread would be to zip the
> > above and take over a file system.

Oops! I see this issue has nothing to do with Perl.

If Mr. Ancheta still has problems with this thread, I suggest that he post
them on the appropriate newsgroup.

Thanks.

Bill Segraves




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

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


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