[21841] in Perl-Users-Digest

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

Perl-Users Digest, Issue: 4045 Volume: 10

daemon@ATHENA.MIT.EDU (Perl-Users Digest)
Wed Oct 30 00:05:53 2002

Date: Tue, 29 Oct 2002 21: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           Tue, 29 Oct 2002     Volume: 10 Number: 4045

Today's topics:
    Re: ---logfile analysis <Dave.BarnettNOSPAM@westerngeco.com>
    Re: [Q] An associative array of file handles <krahnj@acm.org>
    Re: [Q] An associative array of file handles <goldbb2@earthlink.net>
    Re: Can package names be supplied on-the-fly? <jkeen@concentric.net>
    Re: Creating a Microsoft Word file with Win32::OLE (Jay Tilton)
        extract numbers from col/row report <lance@augustmail.com>
    Re: extract numbers from col/row report <wksmith@optonline.net>
        More Efficient Way To Get Last Line From A TXT File <jlim30@hotmail.com>
    Re: More Efficient Way To Get Last Line From A TXT File <kurzhalsflasche@netscape.net>
    Re: Perl, Packages, Solaris and such things (David)
        Recurring problem (Mahamane)
    Re: Recurring problem (Jay Tilton)
    Re: Recurring problem (Tad McClellan)
    Re: Strange Performance Thing (Jan Fure)
        Sybase CGI script fails after upgrade of Solaris OS <bstutes@eskimo.com>
        what is $::DEBUG? <gxz103@yahoo.com>
    Re: what is $::DEBUG? <mjcarman@mchsi.com>
        while vs. foreach (Jan Fure)
    Re: while vs. foreach <ak@freeshell.org.REMOVE>
    Re: while vs. foreach <steven.smolinski@sympatico.ca>
    Re: while vs. foreach <Spam_Sucks@rr.com>
    Re: while vs. foreach <Spam_Sucks@rr.com>
    Re: while vs. foreach <wksmith@optonline.net>
    Re: while vs. foreach <jurgenex@hotmail.com>
        Digest Administrivia (Last modified: 6 Apr 01) (Perl-Users-Digest Admin)

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

Date: Tue, 29 Oct 2002 18:38:24 -0600
From: Dave Barnett <Dave.BarnettNOSPAM@westerngeco.com>
Subject: Re: ---logfile analysis
Message-Id: <apn9n5$d93$1@news.sinet.slb.com>

Bill:

Bill zhao wrote:

>   Thank you very much, it work perfectly, I will need to learn more
> about hash of hashes(HoH)
> But by the way I also need to know why "use warnings;" does not work on
> my pc RH6.2. the pc is has rpm perl (perl-5.00503-12), I did add some cpan
> modules(cannot remember in details,at least including
> Time::HiRes)previously.
> Actually I can find the module file /usr/local/lib/perl5/5.8.0/warnings.pm
> exist there.

If I remember correctly, the "warnings" module did not come into Perl until 
5.6.  You say that your rpm shows perl 5.005..., but you also have perl 5.8 
installed.  Perhaps you need to change from using "#!/usr/local/bin/perl" 
to using "#!/some/path/to/perl5.8/perl" to get the 5.8 version.....

Cheers,
Dave

-- 
Dave Barnett
Pinky: "What statement do rubber pants make?"
Brain: "I've never been potty-trained?"
Pinky: "I'm sorry to hear that, Brain."


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

Date: Wed, 30 Oct 2002 00:05:41 GMT
From: "John W. Krahn" <krahnj@acm.org>
Subject: Re: [Q] An associative array of file handles
Message-Id: <3DBF224C.C599A308@acm.org>

Morden wrote:
> 
> John W. Krahn wrote:
> > Morden wrote:
> >
> >>Suppose I want to write snippets to files instead of pooling the text in
> >>memory ($logtext associative array).
> >
> > If your data was sorted by store number (your hash key) this would be
> > possible.
> >
> It is not sorted.
> 
> >>Is it doable to have an associative
> >>array of filehandles?
> >
> > Yes.
> 
> How would I do this?
> 
> >>}
> >>
> >>while($_=<>) {
> >
> > If you are going to use the special null filehandle you should leave the
> > file names in @ARGV and perl will open the file(s) for you.  If you want
> > to open the file yourself you should use a filehandle other then STDIN.
> >
> I use the input filename to derive the output filename prefix from.
> If none then there's no prefix.
> 
> [snip]
> 
> > You could do it this way without multiple filehandles or a hash:
> >
> > #!/usr/bin/perl -w
> > use strict;
> >
> > die "usage: $0 filename\n" unless @ARGV;
> >
> > while ( <> ) {
> >     my $store = (split /"?\t"?/)[2];
> >     if ( open OUT, ">> $ARGV.$store" ) {
> >         print OUT;
> >         close OUT;
> >         }
> >     }
> >
> > __END__
> 
> This would work albeit I'd have to open and close files all the time.
> And you won't be able to feed some input to it from stdin.
> 
> How does this look to you:
> 
> #!/usr/bin/perl -w
> 
> if ( defined( $PREF = shift ) ) {
>         open(STDIN, $PREF) || die("can't open file $PREF code $!\n");
>         $PREF .= ".";
> } else {
>         # alternatively it could be "stdin."
>         $PREF="";
> }
> 
> while ( <> ) {
>       my $store = (split /"?\t"?/)[2];
>       if ( $store && open OUT, ">>$PREF$store" ) {
>           print OUT;
>           close OUT;
>       }
> }
> 
> (I've dropped "use strict" because perl was complaining:
> Global symbol "$PREF" requires explicit package name at
> /usr/lib/spwww/spwwwlogsplit.pl line 4.


Perhaps this will do what you want:

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

while ( <> ) {
    my $store = (split /"?\t"?/)[2];
    my $file = $ARGV eq '-' ? $store : "$ARGV.$store";
    if ( open OUT, ">> $file" ) {
        print OUT;
        close OUT;
        }
    }

__END__


Or if you want to cache the filehandles so you don't have re-open the
file for each line:

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

my %cache;
while ( <> ) {
    my $store = (split /"?\t"?/)[2];
    my $file = $ARGV eq '-' ? $store : "$ARGV.$store";

    if ( exists $cache{$store} ) {
        print {$cache{$store}};
        }
    elsif ( my $ret = open my $fh, ">> $file" ) {
        print $fh;
        $cache{$store} = $fh;
        }
    elsif ( not defined $ret and %cache ) {
        # couldn't open file so dump the cache and start over
        %cache = ();
        redo;
        }
    else {
        die "Unknown error\n";
        }
    }

__END__







John
-- 
use Perl;
program
fulfillment


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

Date: Tue, 29 Oct 2002 23:33:04 -0500
From: Benjamin Goldberg <goldbb2@earthlink.net>
Subject: Re: [Q] An associative array of file handles
Message-Id: <3DBF6100.14FC0263@earthlink.net>

John W. Krahn wrote:
[snip]
> Or if you want to cache the filehandles so you don't have re-open the
> file for each line:

   use FileCache;

-- 
my $n = 2; print +(split //, 'e,4c3H r ktulrnsJ2tPaeh'
 ."\n1oa! er")[map $n = ($n * 24 + 30) % 31, (42) x 26]


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

Date: 30 Oct 2002 02:39:00 GMT
From: "James E Keenan" <jkeen@concentric.net>
Subject: Re: Can package names be supplied on-the-fly?
Message-Id: <apngo4$n17@dispatch.concentric.net>


"Benjamin Goldberg" <goldbb2@earthlink.net> wrote in message
news:3DBEDC2A.BBD10C85@earthlink.net...
> Randal L. Schwartz wrote:
> >
[snip]
> >
> >     sub my_reprocess_subs {
> >       my $caller_package = shift || caller;
> >       no strict 'refs';
> >       grep { /^reprocess_/ and defined *{$_}{CODE} }
> >         sort keys %{ $caller_package . "::" }
> >     }
>
>
> The keys of %Foo:: are not fully qualified... they are strings like
> "bar".  Checking for defined *{"bar"}{CODE} will check in the *current*
> package.  That was why I qualified my last suggested change with
> pointing out that that $pkg always comes from __PACKAGE__.
>

Thanks for the suggestions.  Within a couple of days I hope to be able to
test both out on site and see which works best.




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

Date: Tue, 29 Oct 2002 23:50:35 GMT
From: tiltonj@erols.com (Jay Tilton)
Subject: Re: Creating a Microsoft Word file with Win32::OLE
Message-Id: <3dbf1d77.113404452@news.erols.com>

Calvin Wong <cawong@cisco.com> wrote:

: Can someone please post a simple code to use Microsoft
: word to open a new document, place "hello world" in it, save
: the file, and then close Microsoft word.

Share the code you already have, even if it falls short of the goal.



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

Date: Tue, 29 Oct 2002 19:22:01 -0600
From: Lance Hoffmeyer <lance@augustmail.com>
Subject: extract numbers from col/row report
Message-Id: <pan.2002.10.30.01.22.01.341660.6007@augustmail.com>

I have these reports I need to extract numbers from and import into excel.
 I am not quite sure where to start but I thought of using a series of if
statements to get to the correct table.

if (m/TEST SUMMARY TABLE/){
   if (m/TEST 2/){

then I will need to grab the 4th percent under TEST 3 (58.9). This is
where I am really drawing a blank and can't figure out how I will get the
number.  Any suggestions?

As an aside I will eventually need to take this number and put it in a
predetermined Excel spreadsheet in col D, row 2.  I know there is an Excel
module but I have never seen or used it. Any suggestions on tutorial,
examples, ...


Lance




TABLE 181
TEST SUMMARY TABLE
Q.DVDTOT
                           
                     TOTAL
                     ACTIV ONLY  RESPS MEMBR MEMBR RESPS MEMBR MEMBR -----
                     ----- ----- ----- ----- ----- ----- -----
                       (A)   (B)   (C)   (D)   (E)   (F)   (G)   (H)
								    
TOC_HYPERLINK
BASE                   483   127   337   258    79*  228   175    53
              							    
              							    
OVERALL TEST(NET)      337    45   337   258    79   228   175    53
                      69.8  35.4 100.0 100.0 100.0 100.0 100.0 100.0
								    
 TEST 2                228    11   228   175    53   228   175    53
                      47.2   8.7  67.7  67.8  67.1 100.0 100.0 100.0
								    
 TEST 3                188    35   188   152    36   113    88    25
                      38.9  27.6  55.8  58.9  45.6  49.6  50.3  47.2


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

Date: Wed, 30 Oct 2002 03:24:42 GMT
From: "Bill Smith" <wksmith@optonline.net>
Subject: Re: extract numbers from col/row report
Message-Id: <_hIv9.19481$TH6.3024@news4.srv.hcvlny.cv.net>


"Lance Hoffmeyer" <lance@augustmail.com> wrote in message
news:pan.2002.10.30.01.22.01.341660.6007@augustmail.com...
> I have these reports I need to extract numbers from and import into excel.
>  I am not quite sure where to start but I thought of using a series of if
> statements to get to the correct table.
>
> if (m/TEST SUMMARY TABLE/){
>    if (m/TEST 2/){
>
> then I will need to grab the 4th percent under TEST 3 (58.9). This is
> where I am really drawing a blank and can't figure out how I will get the
> number.  Any suggestions?
>
--snip--


(split)[3];

Split the line on white space then select the fourth element.

Bill







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

Date: Wed, 30 Oct 2002 08:54:01 +0800
From: Johnny Lim <jlim30@hotmail.com>
Subject: More Efficient Way To Get Last Line From A TXT File
Message-Id: <1jauru8uq63eal84k46c29covglkofmknf@4ax.com>

Hello All,

I'm a new user of Perl and would like to get some help/advice on how to improve
my Perl program efficiently.

I have a project which requires me to read the LAST LINE of my data file every 5
minutes.

My data file structure looks like this:-

"(PDH-CSV 4.0) (Malay Peninsula Standard
Time)(-480)","\\BDC302CTX14\Processor(_Total)\% Processor Time"
"10/25/2002 15:08:13.358","99.997787000987586"
"10/25/2002 15:13:13.358","45.777343733333332"
"10/25/2002 15:18:13.358","41.129557299999995"
"10/25/2002 15:23:13.358","39.420572933333332"
"10/25/2002 15:28:13.358","41.313802066666675"
"10/25/2002 15:33:13.358","47.742838533333334"
"10/25/2002 15:38:13.358","28.370442733333334"
"10/25/2002 15:43:13.358","34.31054686666667"

My Perl source:-

   if ( not open( CSVFILE, $cCSVFile ) )
   {
      print qq(ERROR! ERROR!\n);
      print qq(Cannot Open PERFMON CSV File: $cCSVFile For Reading: $!\n\n);

      exit( 1 );
   }

   #----------------------------------------------------#
   # Read ALL PERFMON CSV Data And Store Into Array     #
   # And Get The Last Line Of Data                      #
   # NOTE: BE Careful Here!! Storing ALL Data From File #
   #       Into Array! Will EAT Up RAM!!                #
   #----------------------------------------------------#
   @CSVData     = <CSVFILE>;                         
   chomp( @CSVData );                                
   @CSVLastLine = split /,/, $CSVData[ $#CSVData ]; 

Is there anyway i can improve the last three lines of the above code and not
using ARRAY to store all the contents of the file?

Thanks In Advance.

Johnny Lim
Malaysia



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

Date: Wed, 30 Oct 2002 02:50:13 +0100
From: Dominik Seelow <kurzhalsflasche@netscape.net>
Subject: Re: More Efficient Way To Get Last Line From A TXT File
Message-Id: <3DBF3AD5.8090702@netscape.net>

Johnny Lim announced:
> Hello All,
> 
> I'm a new user of Perl and would like to get some help/advice on how to improve
> my Perl program efficiently.
> 
> I have a project which requires me to read the LAST LINE of my data file every 5
> minutes.
> 
> My data file structure looks like this:-
> 
> "(PDH-CSV 4.0) (Malay Peninsula Standard
> Time)(-480)","\\BDC302CTX14\Processor(_Total)\% Processor Time"
> "10/25/2002 15:08:13.358","99.997787000987586"
> "10/25/2002 15:13:13.358","45.777343733333332"
> "10/25/2002 15:18:13.358","41.129557299999995"
> "10/25/2002 15:23:13.358","39.420572933333332"
> "10/25/2002 15:28:13.358","41.313802066666675"
> "10/25/2002 15:33:13.358","47.742838533333334"
> "10/25/2002 15:38:13.358","28.370442733333334"
> "10/25/2002 15:43:13.358","34.31054686666667"
> 
> My Perl source:-
> 
>    if ( not open( CSVFILE, $cCSVFile ) )
>    {
>       print qq(ERROR! ERROR!\n);
>       print qq(Cannot Open PERFMON CSV File: $cCSVFile For Reading: $!\n\n);
> 
>       exit( 1 );
>    }
> 
>    #----------------------------------------------------#
>    # Read ALL PERFMON CSV Data And Store Into Array     #
>    # And Get The Last Line Of Data                      #
>    # NOTE: BE Careful Here!! Storing ALL Data From File #
>    #       Into Array! Will EAT Up RAM!!                #
>    #----------------------------------------------------#
>    @CSVData     = <CSVFILE>;                         
>    chomp( @CSVData );                                
>    @CSVLastLine = split /,/, $CSVData[ $#CSVData ]; 
> 
> Is there anyway i can improve the last three lines of the above code and not
> using ARRAY to store all the contents of the file?
> 
> Thanks In Advance.
> 
> Johnny Lim
> Malaysia
> 

use File::ReadBackwards;

HTH,
Dominik



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

Date: 29 Oct 2002 15:31:38 -0800
From: david444williams@yahoo.com (David)
Subject: Re: Perl, Packages, Solaris and such things
Message-Id: <cdca58e3.0210291531.55c1c014@posting.google.com>

Problem solved ... bin includes were in the wrong order in PATH

Everything installed first go!


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

Date: 29 Oct 2002 15:38:16 -0800
From: tourem@nhlbi.nih.gov (Mahamane)
Subject: Recurring problem
Message-Id: <7c7486b8.0210291538.64ffb7b0@posting.google.com>

Fellow perl heads...

I have been using perl on and off for a little over 2 years now and my
knowledge is still limited.
I have a problem that I would like to address to see if someone would
be capable of pointing me the direction of the answer.

what i have basically been trying to do, and so far pretty
successfully is to modify text in an html file.

what i use to make the changes is goes along the lines of this:

open (NEW, ">$newfile"); 
  
open (YEAR, "$new");
 
while (@ydir = <YEAR>){ 
  for ($i=0; $i <= $#ydir; $i++) {
      if ($ydir[$i] =~ s/$ip/$ip/ ){
         $ydir[$i] =~ s/$ip/$newip/;
      }
      print NEW $ydir[$i]; 
   }   
} 
close (YEAR); 
close (NEW); 

$ip being the information that's replaced by $newip...
My problem comes when i have multiple in the html file. 
you can see what the entries look like here:
http://zeus.nhlbi.nih.gov/~tourep/entries.html

there's a problem because $ip is one of multiple fields in one entry.
and in some cases some fiels (from different entries) have similar or
same information. So when i do:
      if ($ydir[$i] =~ s/$ip/$ip/ ){
         $ydir[$i] =~ s/$ip/$newip/;
      }

then all of the $ip's in the html file get changed VS my wanting only
a particular $ip to change because it pertains to 1 particular entry.
This is my #1 problem. I can't seem to narrow the change down to one
$ip.

Now i guess my question is does anyone have suggestions as to what i
can use?
either some different way of reading and parsing the file, or a new
module i can use to solve this problem...

any help is appreciated.
Thanks again

Mahamane T.


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

Date: Wed, 30 Oct 2002 01:58:52 GMT
From: tiltonj@erols.com (Jay Tilton)
Subject: Re: Recurring problem
Message-Id: <3dbf3a09.120720037@news.erols.com>

tourem@nhlbi.nih.gov (Mahamane) wrote:

: what i have basically been trying to do, and so far pretty
: successfully is to modify text in an html file.

[snip]

: So when i do:
:      if ($ydir[$i] =~ s/$ip/$ip/ ){
:         $ydir[$i] =~ s/$ip/$newip/;
:      }
:
:then all of the $ip's in the html file get changed VS my wanting only
:a particular $ip to change because it pertains to 1 particular entry.
:This is my #1 problem. I can't seem to narrow the change down to one
:$ip.

This is essentially the same problem you've asked for help with on at
least three previous occasions.

Don't parse HTML with regexes.  Period.

: you can see what the entries look like here:
: http://zeus.nhlbi.nih.gov/~tourep/entries.html

404.

: Now i guess my question is does anyone have suggestions as to what i
: can use?
: either some different way of reading and parsing the file

An HTML parser module, like, say, HTML::Parser.

Or consider the HTML file to be write-only, and create it anew
whenever the source data changes.



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

Date: Tue, 29 Oct 2002 22:43:19 -0600
From: tadmc@augustmail.com (Tad McClellan)
Subject: Re: Recurring problem
Message-Id: <slrnaruor7.23l.tadmc@magna.augustmail.com>

Mahamane <tourem@nhlbi.nih.gov> wrote:

> I have a problem that I would like to address to see if someone would
> be capable of pointing me the direction of the answer.


Do not use regexes to process HTML (as I said in a followup
to you a couple of months ago).


> open (NEW, ">$newfile"); 


You should always, yes *always*, check the return value from open():

   open (NEW, ">$newfile") or die "could not open '$newfile'  $!";


> open (YEAR, "$new");
              ^    ^
              ^    ^

Those quotes aren't needed, so they should not be there.


> while (@ydir = <YEAR>){ 


This is (still) not doing what you think it is doing.


>       if ($ydir[$i] =~ s/$ip/$ip/ ){
>          $ydir[$i] =~ s/$ip/$newip/;
>       }


You do not need to match twice, once will do. You can replace
the whole "if" with just the substitution:

   $ydir[$i] =~ s/$ip/$newip/;


> Now i guess my question is does anyone have suggestions as to what i
> can use?


You should (still) use a module that understands HTML to process HTML.


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


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

Date: 29 Oct 2002 17:12:53 -0800
From: jan_may2002_fure@attbi.com (Jan Fure)
Subject: Re: Strange Performance Thing
Message-Id: <e47a84bf.0210291712.3adcd28c@posting.google.com>

Sven <un1@bluewin.ch> wrote in message news:<un1-49917D.11204129102002@zinews.unizh.ch>...
> I'm not big in Perl internals, but is it possible that the regex engine 
> uses external libraries that are not usually bundled with Perl (i.e. in 
> the Perl RPM provided by RedHat 8)? I hate to do this, but I might have 
> to rip the whole thing down and install Perl from source. 
> 
> Or could the problem be related to the text encoding? Maybe a library 
> needed to deal with UTF8 missing? I'm really clueless this time.
> 
> Thanks for any hint,   Sven

Pasted text below is from ActivePerl download page, I don't know if
the RPM of standard per is affected.

Jan

(*) Note: Do not install the ActivePerl RPM on Red Hat Linux 8.0. 
A bug in the current Red Hat distribution may corrupt the RPM
database. Instead, use the tarball distributions of ActivePerl
(.tar.gz). The Red Hat team has been advised of this issue. More
information about this bug is avalaible at the RedHat Bug Tracking
System

http://www.activestate.com/Products/Download/Download.plex?id=ActivePerl


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

Date: Tue, 29 Oct 2002 20:15:04 -0600
From: Bob Stutes <bstutes@eskimo.com>
Subject: Sybase CGI script fails after upgrade of Solaris OS
Message-Id: <3DBF40A8.2090001@eskimo.com>

Actually, we had to rebuild the machine since the root disk on the 
machine blew chunks.

Anyway, here's the story:

The script in question is a cgi the uses the old Sybperl interface to 
the Sybase client libs.  Under Solaris 2.6 and perl 5.004 this allworked 
just fine (please be kind ... this box is hosting a legacy server so 
we're kinda stuck with the obsolete methods for getting to Sybase).

The machine was rebuilt as a Solaris 8 server.  Still using the 
executables and modules from the original 2.6 server.  BTWm the web 
server is Netscape Suitespot v3.6.

Now when the server runs a script that uses the Sybperl modules, Perl 
aborts while loading the script complaining that ld cannot resolve a 
reference to a symbol in a nested Sybase library.

In particular, CTlib.so has dynamic references to entry points in 
libtcl.so.  No problem here.  libtcl.so has references to dymanic entry 
points in libcomn.so.  It in this context (libtcl.so -> libcomn.so) that 
   the run time linker shoots craps and give up.

Was there a change in the dynamic linking subsystem between Solaris 2.6 
and Solaris 8 that is causing this rpoblem?  Does anyone know if there 
is a work around for this?

I have moved a number of executables from Sol 2.6 to Sol 8 with no 
problem.  This is a first.

TIA.
-- 
Bob Stutes - St. Louis, Mo.
Unix Administrator and General Geek Wanna-Be
e-mail: bstutes@eskimo.com

The Wisdom of the ages may be found ... if you will only look up.
                                           Unknown.



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

Date: Tue, 29 Oct 2002 15:50:21 -0800
From: "Bill Zhou" <gxz103@yahoo.com>
Subject: what is $::DEBUG?
Message-Id: <apn6pv$lek$1@news01.intel.com>

hi,
   I see statement:
   $::DEBUG{Options} = 0;
 in some code.  Does anyone know what is $::DEBUG ?

Thanks.




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

Date: Wed, 30 Oct 2002 00:38:09 GMT
From: Michael Carman <mjcarman@mchsi.com>
Subject: Re: what is $::DEBUG?
Message-Id: <RRFv9.4780$iW.4933@rwcrnsc52.ops.asp.att.net>

On 10/29/2002 5:50 PM, Bill Zhou wrote:
>
>    I see statement:
>    $::DEBUG{Options} = 0;
>  in some code.  Does anyone know what is $::DEBUG ?

It's the global variable %DEBUG in the main:: namespace. That is, it's
shorthand for $main::DEBUG{Options}. There's nothing special about it,
it's just a user-defined variable -- presumably holding debugging
parameters...

-mjc



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

Date: 29 Oct 2002 17:06:47 -0800
From: jan_may2002_fure@attbi.com (Jan Fure)
Subject: while vs. foreach
Message-Id: <e47a84bf.0210291706.ca49500@posting.google.com>

Hi;

I just resolved a problem involving code looking like:

open(CURRENT,">>$name" . "_" . "$n3" . ".txt");
foreach (@tempdata) {
    print CURRENT (shift @tempdata);
}
close CURRENT;

My intention was to move values from the "@tampdata" array to the
output file, and the code above does that in an unreliable manner,
meaning some lines of the file getting processed are MIA.

I am sure Perl is doing exactly what I am telling it to do, and in
retrospect I can see that the loop below MUST keep executing until
there is nothing left of the array being processed.

The reason I am posting a question is that since I don't know what was
wrong, it is not clear to me that my fix is permanent.

Is there any problem with the code below too? And what is the
differense compared to code above?

open(CURRENT,">>$name" . "_" . "$n3" . ".txt");
while (@tempdata) {
    print CURRENT (shift @tempdata);
}
close CURRENT;

Jan Fure, 
Perl novice


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

Date: Wed, 30 Oct 2002 01:32:21 -0000
From: Andreas =?iso-8859-1?Q?K=E4h=E4ri?= <ak@freeshell.org.REMOVE>
Subject: Re: while vs. foreach
Message-Id: <slrnarudke.2o8.ak@otaku.freeshell.org>

Submitted by "Jan Fure" to comp.lang.perl.misc:
> Hi;
> 
> I just resolved a problem involving code looking like:
> 
> open(CURRENT,">>$name" . "_" . "$n3" . ".txt");
> foreach (@tempdata) {
>     print CURRENT (shift @tempdata);
> }
> close CURRENT;

Consider this program:

use strict;
my @arr = qw( a b c d e f g h i );
foreach (@arr) {
    print shift @a;
}

Output:
abcde


You're modifying the contents of the array as you iterate over
it.  Instead, you should have done the equivalent of

use strict;
my @arr = qw( a b c d e f g h i );
foreach (@arr) {
    print;
}

or

use strict;
my @arr = qw( a b c d e f g h i );
foreach my $item (@arr) {
    print $item;
}


> 
> My intention was to move values from the "@tampdata" array to the
> output file, and the code above does that in an unreliable manner,
> meaning some lines of the file getting processed are MIA.
> 
> I am sure Perl is doing exactly what I am telling it to do, and in
> retrospect I can see that the loop below MUST keep executing until
> there is nothing left of the array being processed.
> 
> The reason I am posting a question is that since I don't know what was
> wrong, it is not clear to me that my fix is permanent.
> 
> Is there any problem with the code below too? And what is the
> differense compared to code above?
> 
> open(CURRENT,">>$name" . "_" . "$n3" . ".txt");
> while (@tempdata) {
>     print CURRENT (shift @tempdata);
> }
> close CURRENT;

You're still modifying the array in the loop, but now it's ok
since 'while' just tests for a condition.  'foreach', on the
other hand, assigns each value of the array to $_.  

> 
> Jan Fure, 
> Perl novice

See the perlsyn manual ("perldoc perlsyn").

-- 
Andreas Kähäri               --==::{ Have a Unix: netbsd.org
                             --==::{ This post ends with :wq


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

Date: Wed, 30 Oct 2002 03:09:59 GMT
From: Steven Smolinski <steven.smolinski@sympatico.ca>
Subject: Re: while vs. foreach
Message-Id: <b4Iv9.2641$qD2.718009@news20.bellglobal.com>

Andreas Kähäri <ak@freeshell.org.REMOVE> wrote:
 
> You're modifying the contents of the array as you iterate over
> it.  Instead, you should have done the equivalent of
> 
> use strict;
> my @arr = qw( a b c d e f g h i );
> foreach (@arr) {
>     print;
> }

There is always:

print @arr;

HTH.

Steve


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

Date: Wed, 30 Oct 2002 03:29:49 GMT
From: "Luther Barnum" <Spam_Sucks@rr.com>
Subject: Re: while vs. foreach
Message-Id: <NmIv9.28826$fa.573116@twister.tampabay.rr.com>


"Jan Fure" <jan_may2002_fure@attbi.com> wrote in message
news:e47a84bf.0210291706.ca49500@posting.google.com...
> Hi;
>
> I just resolved a problem involving code looking like:
>
> open(CURRENT,">>$name" . "_" . "$n3" . ".txt");
> foreach (@tempdata) {
>     print CURRENT (shift @tempdata);
> }
> close CURRENT;
>
> My intention was to move values from the "@tampdata" array to the
> output file, and the code above does that in an unreliable manner,
> meaning some lines of the file getting processed are MIA.
>
> I am sure Perl is doing exactly what I am telling it to do, and in
> retrospect I can see that the loop below MUST keep executing until
> there is nothing left of the array being processed.
>
> The reason I am posting a question is that since I don't know what was
> wrong, it is not clear to me that my fix is permanent.
>
> Is there any problem with the code below too? And what is the
> differense compared to code above?
>
> open(CURRENT,">>$name" . "_" . "$n3" . ".txt");
> while (@tempdata) {
>     print CURRENT (shift @tempdata);
> }
> close CURRENT;
>
> Jan Fure,
> Perl novice
>
How about:

open(CURRENT,">>$name" . "_" . "$n3" . ".txt");
foreach $line (@tempdata) {
    chomp($line);
    print CURRENT ("$line\n");
)
close CURRENT;


or easier to read

$newfile = $name" . "_" . "$n3" . ".txt";
open(CURRENT,">>$newfile);
foreach $line (@tempdata) {
    chomp($line);
    print CURRENT ("$line\n");
)
close CURRENT;





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

Date: Wed, 30 Oct 2002 03:34:27 GMT
From: "Luther Barnum" <Spam_Sucks@rr.com>
Subject: Re: while vs. foreach
Message-Id: <7rIv9.28865$fa.573623@twister.tampabay.rr.com>

This works but my version does allow later modification to the variable and
for a newbie, there are enough steps in the example to be of use later on.
No disrespect intended.

Luther


"Steven Smolinski" <steven.smolinski@sympatico.ca> wrote in message
news:b4Iv9.2641$qD2.718009@news20.bellglobal.com...
> Andreas Kähäri <ak@freeshell.org.REMOVE> wrote:
>
> > You're modifying the contents of the array as you iterate over
> > it.  Instead, you should have done the equivalent of
> >
> > use strict;
> > my @arr = qw( a b c d e f g h i );
> > foreach (@arr) {
> >     print;
> > }
>
> There is always:
>
> print @arr;
>
> HTH.
>
> Steve
>




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

Date: Wed, 30 Oct 2002 03:57:04 GMT
From: "Bill Smith" <wksmith@optonline.net>
Subject: Re: while vs. foreach
Message-Id: <kMIv9.19776$TH6.4572@news4.srv.hcvlny.cv.net>


"Jan Fure" <jan_may2002_fure@attbi.com> wrote in message
news:e47a84bf.0210291706.ca49500@posting.google.com...
> Hi;
>
> I just resolved a problem involving code looking like:
>
> open(CURRENT,">>$name" . "_" . "$n3" . ".txt");
> foreach (@tempdata) {
>     print CURRENT (shift @tempdata);
> }
> close CURRENT;
>
> My intention was to move values from the "@tampdata" array to the
> output file,
--snip--

Your fix does work correctly, but a loop is not necessary at all.  You can
use the OUTPUT_RECORD_SEPARATOR ($,) to supply
newlines if they are not in the array.

{
    local $, = "\n";
    print CURRENT @tempdata;
}




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

Date: Wed, 30 Oct 2002 04:13:27 GMT
From: "Jürgen Exner" <jurgenex@hotmail.com>
Subject: Re: while vs. foreach
Message-Id: <H%Iv9.33377$iV1.1962@nwrddc02.gnilink.net>

Jan Fure wrote:
> I just resolved a problem involving code looking like:
>
> open(CURRENT,">>$name" . "_" . "$n3" . ".txt");
> foreach (@tempdata) {
>     print CURRENT (shift @tempdata);

Get rid of the "shift". You are deleting elements from the array while in a
for loop. That screws things up.
Excerpt from "perldoc perlsyn":
   If any part of LIST is an array, `foreach' will get very confused if you
   add or remove elements within the loop body, for example with `splice'.
   So don't do that.

> }
> close CURRENT;

> My intention was to move values from the "@tampdata" array to the
> output file, and the code above does that in an unreliable manner,

So, don't shoot yourself in the foot. You have been warned ;-)

[...]
> open(CURRENT,">>$name" . "_" . "$n3" . ".txt");
> while (@tempdata) {
>     print CURRENT (shift @tempdata);
> }
> close CURRENT;

In this case you are not looping over each element of the array.
Instead you are repeating the while loop as long as the array is not empty.
Quite a different logic.

jue




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

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


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