[17461] in Perl-Users-Digest

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

Perl-Users Digest, Issue: 4881 Volume: 9

daemon@ATHENA.MIT.EDU (Perl-Users Digest)
Mon Nov 13 21:06:17 2000

Date: Mon, 13 Nov 2000 18:05:09 -0800 (PST)
From: Perl-Users Digest <Perl-Users-Request@ruby.OCE.ORST.EDU>
To: Perl-Users@ruby.OCE.ORST.EDU (Perl-Users Digest)
Message-Id: <974167508-v9-i4881@ruby.oce.orst.edu>
Content-Type: text

Perl-Users Digest           Mon, 13 Nov 2000     Volume: 9 Number: 4881

Today's topics:
    Re: A surprise with vec() (Martien Verbruggen)
    Re: A surprise with vec() (Gwyn Judd)
        algorith help: combining similar lines (Adam Spragg)
    Re: algorith help: combining similar lines (Martien Verbruggen)
    Re: algorith help: combining similar lines <wyzelli@yahoo.com>
    Re: Comparing textfiles <tim@ipac.caltech.edu>
        File Upload Problem - PLS HELP! fhinchey@my-deja.com
    Re: File Upload Problem - PLS HELP! <jeff@vpservices.com>
        IP geography tcblue@my-deja.com
        perl -> vbscript <alex@hoopsie2.com>
    Re: perl -> vbscript (Chris Fedde)
        Perl bug? <braz@students.uiuc.edu>
    Re: Perl bug? (John J. Trammell)
    Re: Perl bug? (Martien Verbruggen)
    Re: Perl bug? (Richard J. Rauenzahn)
        Problem with chomp and print <arm@home.com>
    Re: Problem with chomp and print (Martien Verbruggen)
    Re: Realrates.com needs your Rate and Salary Data! <nospam@david-steuber.com>
    Re: Removing New Page character from a text file (Garry Williams)
        sharing data between processes <root@prettyfly.iinet.net.au>
    Re: sharing data between processes <bwalton@rochester.rr.com>
    Re: Statistics for comp.lang.perl.misc <nospam@david-steuber.com>
        writing on certain records in a file <arm@home.com>
        Digest Administrivia (Last modified: 16 Sep 99) (Perl-Users-Digest Admin)

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

Date: Tue, 14 Nov 2000 10:06:05 +1100
From: mgjv@tradingpost.com.au (Martien Verbruggen)
Subject: Re: A surprise with vec()
Message-Id: <slrn910sut.gs3.mgjv@martien.heliotrope.home>

On Mon, 13 Nov 2000 17:49:33 GMT,
	Gwyn Judd <tjla@guvfybir.qlaqaf.bet> wrote:
> I was shocked! How could Bart Lateur <bart.lateur@skynet.be>
> say such a terrible thing:
>>
>>	$x = "0";
>>	print ord $x;
> 
> or the surprising:
> 
> $x = 0;
> print ord $x;

It's only surprising when if don't realise that ord always works on the
first character of the string value of the expression. In this case, it
would hardly be useful to do anything else. The ord() function is
supposed to return the numeric value of a character. The integer 0 isn't
a character, it's an integer, so Perl converts.

Martien
-- 
Martien Verbruggen              | 
Interactive Media Division      | Make it idiot proof and someone will
Commercial Dynamics Pty. Ltd.   | make a better idiot.
NSW, Australia                  | 


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

Date: Tue, 14 Nov 2000 01:54:27 GMT
From: tjla@guvfybir.qlaqaf.bet (Gwyn Judd)
Subject: Re: A surprise with vec()
Message-Id: <slrn9116qh.4g0.tjla@thislove.dyndns.org>

I was shocked! How could Martien Verbruggen <mgjv@tradingpost.com.au>
say such a terrible thing:

>It's only surprising when if don't realise that ord always works on the
>first character of the string value of the expression. In this case, it
>would hardly be useful to do anything else. The ord() function is
>supposed to return the numeric value of a character. The integer 0 isn't
>a character, it's an integer, so Perl converts.

Well it was surprisingish in comparison with the $x = "0" one that
someone else had posted. Especially when you consider I had initialised
$x as a number. I guess it's because of my C background. In C there
isn't really any equivalen of ord() to speak of since there isn't really
any distinction between characters and numbers.

-- 
Gwyn Judd (print `echo 'tjla@guvfybir.qlaqaf.bet' | rot13`)
Your salary will be increased.


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

Date: 13 Nov 2000 23:21:24 GMT
From: atspragg@garbanzo.engr.ucdavis.edu (Adam Spragg)
Subject: algorith help: combining similar lines
Message-Id: <8upt1k$qgg$1@mark.ucdavis.edu>

Hello all...

I have a text file that looks like this

ABCD, 100, DEF, GHI, JKL
ABCD, 50, DEF, GHI, JKL
ABCD, 1000, DEF, GHI, JKL
XYZ, 100, IJK, LMN, OPQ
XYZ, 200, IJK, LMN, OPQ

As ouput, I'd like the sum totals for each grouping:

ABCD, 1150, DEF, GHI, JKL
XYZ, 300, IJK, LMN, OPQ

Any ideas?  I wrote something which is pretty ugly (double while loop) 
which reads a line, then reads in the rest of the lines, does some 
matching, etc...  But is there a better way?  And this being Perl-y, the 
answer is probably "yes."

Please POST responses.

Adam


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

Date: Tue, 14 Nov 2000 11:03:47 +1100
From: mgjv@tradingpost.com.au (Martien Verbruggen)
Subject: Re: algorith help: combining similar lines
Message-Id: <slrn9110b3.gs3.mgjv@martien.heliotrope.home>

On 13 Nov 2000 23:21:24 GMT,
	Adam Spragg <atspragg@garbanzo.engr.ucdavis.edu> wrote:
> Hello all...
> 
> I have a text file that looks like this
> 
> ABCD, 100, DEF, GHI, JKL
> ABCD, 50, DEF, GHI, JKL
> ABCD, 1000, DEF, GHI, JKL
> XYZ, 100, IJK, LMN, OPQ
> XYZ, 200, IJK, LMN, OPQ
> 
> As ouput, I'd like the sum totals for each grouping:
> 
> ABCD, 1150, DEF, GHI, JKL
> XYZ, 300, IJK, LMN, OPQ

Your specification is slightly ambiguous. Is the unique thing you want
to count a combination of the fields 0, 2, 3, and 4, or is only field 0
important?

In other words, you should probably define what 'grouping' means.

> Any ideas?  I wrote something which is pretty ugly (double while loop) 
> which reads a line, then reads in the rest of the lines, does some 
> matching, etc...  But is there a better way?  And this being Perl-y, the 
> answer is probably "yes."

If all fields count (which your example seems to suggest), this is a
possible solution:

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

my %count;
while (<DATA>)
{
	chomp;
	my ($start, $num, $end) = split /, /, $_, 3;
	$count{$start, $end} += $num; # see note [1]
}

while (my ($key, $val) = each %count)
{
	my ($start, $end) = split /$;/, $key, 2;
	print join ', ', $start, $val, $end;
}

__DATA__
ABCD, 100, DEF, GHI, JKL
ABCD, 50, DEF, GHI, JKL
ABCD, 1000, DEF, GHI, JKL
XYZ, 100, IJK, LMN, OPQ
XYZ, 200, IJK, LMN, OPQ
XYZ, 200, ABC, LMN, OPQ
XYZ, 200, ABC, LMN, OPQ

If the key is the first field only, then it makes no sense outputting
the rest of the lines, and you'd end up with something much simpler:

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

my %count;
while (<DATA>)
{
    chomp;
    my ($start, $num, $end) = split /, /, $_, 3;
    $count{$start} += $num;
}

while (my ($key, $val) = each %count)
{
    print "$key, $val";
}

# __DATA__ omitted, see above

Of course, there are other ways of doing this. One could make the key
the first field, and count a total. Then one could subtotal the
combination of the 3rd, 4th and 5th field, or anything like that. If
that's necessary, give it a try, and if you can't work it out, post here
again, describing the problem in a bit more detail.

Martien

[1] See the entry for $; in perlvar for a description of
multidimensional array emulation. Of course, you're free to do an
explicit join or concatenation to generate the key for the hash.
-- 
Martien Verbruggen              | 
Interactive Media Division      | That's not a lie, it's a
Commercial Dynamics Pty. Ltd.   | terminological inexactitude.
NSW, Australia                  | 


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

Date: Tue, 14 Nov 2000 10:01:12 +0930
From: "Wyzelli" <wyzelli@yahoo.com>
Subject: Re: algorith help: combining similar lines
Message-Id: <QE%P5.3$eK.3542@vic.nntp.telstra.net>

"Adam Spragg" <atspragg@garbanzo.engr.ucdavis.edu> wrote in message
news:8upt1k$qgg$1@mark.ucdavis.edu...
> Hello all...
>
> I have a text file that looks like this
>
> ABCD, 100, DEF, GHI, JKL
> ABCD, 50, DEF, GHI, JKL
> ABCD, 1000, DEF, GHI, JKL
> XYZ, 100, IJK, LMN, OPQ
> XYZ, 200, IJK, LMN, OPQ
>
> As ouput, I'd like the sum totals for each grouping:
>
> ABCD, 1150, DEF, GHI, JKL
> XYZ, 300, IJK, LMN, OPQ
>

This uses an array stored in a hash with the first field as the key.
Note this does not preserve the order of the lines, though that is
possible if desired, but takes a little more effort.  I sorted the
output cos I felt like it.

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

my %data;

open (IN,'d:/test.txt') or die "Cant $!";
while (<IN>){
    my($key,@array) = /(\w+)/g; # use first field as key
    $data{$key}[0] += $array[0]; # autoincrement field #2 whilst
poulating hash
    foreach my $i (1..$#array){ # populate rest of hash
        $data{$key}[$i] = $array[$i];
    }
}

close IN;

# print it out Note line order is not preserved
foreach my $key (sort(keys(%data))){
    print "$key, $data{$key}[0], $data{$key}[1], $data{$key}[2],
$data{$key}[3]\n";
}



Have fun!

Wyzelli
--
($a,$b,$w,$t)=(' bottle',' of beer',' on the wall','Take one down, pass
it around');
for(reverse(1..100)){$s=($_!=1)?'s':'';$c.="$_$a$s$b$w\n$_$a$s$b\n$t\n";
$_--;$s=($_!=1)?'s':'';$c.="$_$a$s$b$w\n\n";}print"$c*hic*";







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

Date: Mon, 13 Nov 2000 17:26:33 -0800
From: Tim Conrow <tim@ipac.caltech.edu>
Subject: Re: Comparing textfiles
Message-Id: <3A1094C9.3C89E6AA@ipac.caltech.edu>

xarbosa wrote:
> I have two textfiles with the same layout of data.
> I first want to check if the names in file1 already exist in file2, and if
> it does I want to compare dates to select the latest version. The entries in
> the textfiles can be indefinite.
> 
> In the following example I want to see that name1.jpg exists in both files >
> then compare the dates and output the name1.jpg with the newer date:
> 
> File1.txt >  name1.jpg, size, date
>                  name2.jpg, size, date
> 
> File2.txt > name1.jpg, size, (newer)date
>                  name3.jpg, size, date

The solution I offer here is a bit advanced because it involves references. But
you'll have to learn about them sooner or later, so grab the man pages, dig in
and take it from here:

1) Remember 'use strict' and 'use warnings'. For a small increase in effort you
gain tremendous support from perl.

use strict;   # Read the man pages on strict and warnings
use warnings;

2) Read and parse the file. Untested:

my @fields; # read perlfunc for my. read perldata to read about arrays.
my %files;  # read perldata to read about hashes.
for my $file (@filelist) { # perlsyn to read about for/while loops
  open FILE,$file or die "Bad $file; $!"; # perlfunc to read about open and die
  while(<FILE>) { # perlop for I/O operators and perlvar about $_
    s/^\s*//; # perlre and perlop about substitution
    s/\s*$//;
    @fields = split /\s*,\s*/; # perlre and perlfunc for split
    # Keep track of the data for the file with the latest date
    if(! exists $files{$fields[0]} || $fields[2] gt $files{$fields[0]}[2]) {
      my $n=0;
      if(exists $files{$fields[0]}) { $n = $files{$fields[0]}[3] }
      $files{$fields[0]} = [@fields,++$n]; # perlref
    }
  }
}

Dates must sort lexically for this to work, so dates like 'YYYY-MM-DD' (or
'YY-MM-DD' if all your dates are in or after 2000) are OK. If your dates are not
in this form, you'll have to convert them either into this or some other
lexically sortable form or a numeric form (such as "Unix time").

3) Print results. Untested:

for (keys %files) { # perlfunc for keys
  next if $files{$_}[3] < 2; # Only print recurring files.
  print "File: '$files{$_}[0]'  Size: $files{$_}[1]  ".
        "Revision: $files{$_}[2]  Number: $files{$_}[3]\n";
}


This is more verbose than I would write for myself and I hope that makes things
clearer rather than just confusing. Please read the docs and understand how this
works before posting follow-up questions. (Sorry about any typos or goofs. I'm
sure you'll find them!)

--

-- Tim Conrow         tim@ipac.caltech.edu                           |


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

Date: Tue, 14 Nov 2000 00:57:48 GMT
From: fhinchey@my-deja.com
Subject: File Upload Problem - PLS HELP!
Message-Id: <8uq2mb$sn8$1@nnrp1.deja.com>

I'm at my wits end. I have a file upload perl script that is sitting in
my cgi directory. It works fine for uploading to the cgi directory but
doesn't work for uploading to the web root. I have read/write access to
the root so I don't have a clue what the problem is. The error message
I get is "can't open file." From looking at my code can anyone see an
obvious problem. I would appreciate ANY help. Thanks!  --Frank

-----
use CGI qw/:standard/;

print header,
    start_html('file upload'),
    h1('file upload');

print_form()    unless param;
print_results() if param;
print end_html;

sub print_form {
    print start_multipart_form(),
       filefield(-name=>'upload',-size=>60),br,
       submit(-label=>'Upload File'),
       end_form;
}

sub print_results {
    $filename = param('upload');
    $short_filename = param('upload');
    $short_filename =~ s/.*(\\)//;

    open (OUTFILE,">>..web/images/logos/$short_filename") || die "can't
open file";
    while ($bytesread=read($filename,$buffer,1024)) {
       print OUTFILE $buffer;
    }
    close $filename;
    }
}
----


Sent via Deja.com http://www.deja.com/
Before you buy.


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

Date: Mon, 13 Nov 2000 17:18:11 -0800
From: Jeff Zucker <jeff@vpservices.com>
Subject: Re: File Upload Problem - PLS HELP!
Message-Id: <3A1092D3.D29E8B98@vpservices.com>

fhinchey@my-deja.com wrote:
> 
>     open (OUTFILE,">>..web/images/logos/$short_filename") || die "can't
> open file";

#1.  When checking an open, always print $! since that holds the actual
error message to tell you why the file can't be opened.

#2.  You are using a relative address.  What is that address relative
to?  The directory where your script is physically located may or may
not what your server treats as the current directory.

-- 
Jeff


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

Date: Mon, 13 Nov 2000 23:00:52 GMT
From: tcblue@my-deja.com
Subject: IP geography
Message-Id: <8uprqv$n1n$1@nnrp1.deja.com>

Hi,
does any know if there is a perl module or script that can 'try' and
detect the physical location of a given IP address or hostname?  I
found this site that gives a pretty good description of how to make an
educated guess on it.  I know there is no real solid way of doing this,
but i'd like to start collecting geographical information of IP
address.  please let me know If you have any ideas or if there is
already something out there that does this.  Thanks,

-Patrick T.-
tcblue82@yahoo.com


Sent via Deja.com http://www.deja.com/
Before you buy.


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

Date: Tue, 14 Nov 2000 01:21:03 GMT
From: AP <alex@hoopsie2.com>
Subject: perl -> vbscript
Message-Id: <3A109314.44AC61ED@hoopsie2.com>

Can anyone recommend a book for learning vbscript for someone (i.e me)
coming from a perl background?  

(I hope I don't get chewed out for posting this in perl NG--I didn't know
who would know better--ex perlers, or current perlers :) )

Thanks!

Alex

-- 
--------------------------------------------------
  alex@hoopsie2.com  |  http://alex.hoopsie.com
--------- remove the "2" from e-mail -------------


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

Date: Tue, 14 Nov 2000 01:59:19 GMT
From: cfedde@fedde.littleton.co.us (Chris Fedde)
Subject: Re: perl -> vbscript
Message-Id: <X%0Q5.405$Bf7.171119104@news.frii.net>

In article <3A109314.44AC61ED@hoopsie2.com>, AP  <alex@hoopsie2.com> wrote:
>Can anyone recommend a book for learning vbscript for someone (i.e me)
>coming from a perl background?  
>

Your not likely to get much help from this crowd.  Go to a news
group that has vbscript somewhere in the title and ask your question
there.

Good Luck
chris
-- 
    This space intentionally left blank


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

Date: Mon, 13 Nov 2000 17:10:58 -0600
From: Rodrigo de Salvo Braz <braz@students.uiuc.edu>
Subject: Perl bug?
Message-Id: <Pine.GSO.4.10.10011131710290.7154-100000@ux10.cso.uiuc.edu>

Hello,

Can anyone explain me why don't I get @p and @q equal with this
little program? Note: if I use functions other than the CGI cookie
function, then I do get equal arrays!

Thanks in advance, Rodrigo

use CGI qw(:standard);

$query = new CGI;

$x = $query->cookie('key');
$y = $query->self_url;
@p = ($x, $y);

@q = ($query->cookie('key'), $query->self_url);

print
"p:\n",
'(', join(', ', @p), ")\n",
"Size of p: ", ($#p + 1), "\n\n", # this will be 2
"q:\n",
'(', join(', ', @q), ")\n",
"Size of q: ", ($#q + 1), "\n\n"; # but this will be 1 !



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

Date: 13 Nov 2000 23:25:11 GMT
From: trammell@nitz.hep.umn.edu (John J. Trammell)
Subject: Re: Perl bug?
Message-Id: <slrn9103mi.ic4.trammell@nitz.hep.umn.edu>

On Mon, 13 Nov 2000 17:10:58 -0600, Rodrigo de Salvo Braz
<braz@students.uiuc.edu> wrote:
>Hello,
>
>Can anyone explain me why don't I get @p and @q equal with this
>little program? Note: if I use functions other than the CGI cookie
>function, then I do get equal arrays!
>
>Thanks in advance, Rodrigo
>
>use CGI qw(:standard);
>
>$query = new CGI;
>
[snip]

I think you need to decide whether or not you're going to
use CGI in its OO or function-oriented style before you
go any futher.

-- 
John J. Trammell
johntrammell@yahoo.com


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

Date: Tue, 14 Nov 2000 11:20:22 +1100
From: mgjv@tradingpost.com.au (Martien Verbruggen)
Subject: Re: Perl bug?
Message-Id: <slrn9111a6.gs3.mgjv@martien.heliotrope.home>

On Mon, 13 Nov 2000 17:10:58 -0600,
	Rodrigo de Salvo Braz <braz@students.uiuc.edu> wrote:
> Hello,
> 
> Can anyone explain me why don't I get @p and @q equal with this
> little program? Note: if I use functions other than the CGI cookie
> function, then I do get equal arrays!
> 
> Thanks in advance, Rodrigo
> 
> use CGI qw(:standard);

If you are going to use CGI in object mode, you probably shouldn't
include the :standard export tag.

> $query = new CGI;
> 
> $x = $query->cookie('key');
> $y = $query->self_url;
> @p = ($x, $y);

Both methods have been called in scalar context.

> @q = ($query->cookie('key'), $query->self_url);

Both methods are called in list context.

> print
> "p:\n",
> '(', join(', ', @p), ")\n",
> "Size of p: ", ($#p + 1), "\n\n", # this will be 2
> "q:\n",
> '(', join(', ', @q), ")\n",
> "Size of q: ", ($#q + 1), "\n\n"; # but this will be 1 !

The only thing I can think of is that either the cookie() or the
self_url() method returns an empty list in list context, in case it
wants to return failure. 

I'll just take a wild stab here, and guess that the cookie with name
'key' is not set in the environment. That means that cookie() will
probably return with a failure indication, which in Perl is most often
done with a bare return statement, with no value specified.
A bare return in a sub in scalar context returns undef, but in list
context returns the empty list[1].

let's test this.

# perl -wl
use CGI;
my $q = CGI->new;

my $x = $q->cookie('key');
my @x = $q->cookie('key');

print "\$x is ", (defined $x ? '' : 'not '), "defined";
print "\@x contains ", scalar @x, " elements";
__END__
$x is not defined
@x contains 0 elements

Looks like that's it. Many subs in Perl respond differently in list and
scalar context. Especially when they signal failure (by using a bare
return), the return value is different.

Martien

[1] The cookie() method does indeed behave differently in scalar and
list context. Read the code. It's a good idea to do that anyway, since
the cookie method actually does more than is documented.
-- 
Martien Verbruggen              | 
Interactive Media Division      | +++ Out of Cheese Error +++ Reinstall
Commercial Dynamics Pty. Ltd.   | Universe and Reboot +++
NSW, Australia                  | 


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

Date: 14 Nov 2000 00:52:48 GMT
From: nospam@hairball.cup.hp.com (Richard J. Rauenzahn)
Subject: Re: Perl bug?
Message-Id: <974163167.460531@hpvablab.cup.hp.com>





Rodrigo de Salvo Braz <braz@students.uiuc.edu> writes:
>Hello,
>
>Can anyone explain me why don't I get @p and @q equal with this
>little program? Note: if I use functions other than the CGI cookie
>function, then I do get equal arrays!

I think what your question really is...  is..  why are @a and @b
different in the following program?

#!/opt/perl5/bin/perl -w
use strict;

sub foo { return }  # or return () 

my $x = foo;
my $y = 1;

my @a = ($x, $y);
my @b = (foo, $y);

printf "%d,%d\n", scalar @a, scalar @b;

__EOF__

When I put 'sub foo' into the ()'s, think of it as '@a = ((),1)' --
However, when I assign foo() to $x, it is evaluated in scalar context
and $x is set to be undefined -- which I place explicitly into @a above,
giving an array with two elements instead of one.

See the perlsub man page:

	If you specify no return value, the subroutine returns an empty
	list in list context, the undefined value in scalar context, or
	nothing in void context.

Now, what I'm not sure about is why CGI::cookie is returning an empty
list occasionally instead of an undefined scalar.  The CGI man page or
author would have to make the call as to whether that's a bug or a
feature.

Rich
-- 
Rich Rauenzahn ----------+xrrauenza@cup.hp.comx+ Hewlett-Packard Company
Technical Consultant     | I speak for me,     |   19055 Pruneridge Ave. 
Development Alliances Lab|            *not* HP |                MS 46TU2
ESPD / E-Serv. Partner Division +--------------+---- Cupertino, CA 95014


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

Date: Mon, 13 Nov 2000 23:44:00 GMT
From: Alan Melton <arm@home.com>
Subject: Problem with chomp and print
Message-Id: <3A107C10.88A28DAF@home.com>

starting with a file as below

t-adam03@cougar.com
10
30
2000
46.15
2.65
2.50
51.30
Call
@
0-06-093195-7
STAFF
12499
1
9.05
9.05
ODYSSEY OF HOMER (TRANS LATTIMORE)(PERENNIAL (New)0-06-093195-7
0-226-30784-0
STAFF
12499
1
9.30
9.30
EURIPIDES V: THREE TRAGEDIES (P) (New)0-226-30784-0
0-226-30780-8
STAFF
12499
1
9.25
9.25
EURIPIDES I: FOUR TRAGEDIES (P) (New)0-226-30780-8
0-226-30792-1
STAFF
12499
1
9.30
9.30
SOPHOCLES I: THREE TRAGEDIES (P) (New)0-226-30792-1
0-87220-390-5
STAFF
ALL
1
9.25
9.25
ORESTEIA (TRANS MEINECK) (P) (New)0-87220-390-5


By using this program:

  @a = <IN>; # read all lines of this file
  chomp (@vals=@a[1,2,3,10,13,14,15]);
  print OUTPUT join ("  ",@vals), "\n";
  chomp (@vals=@a[1,2,3,17,20,21,22]);
  print OUTPUT join ("  ",@vals), "\n";
  print unless $a eq /^$/;
  chomp (@vals=@a[1,2,3,24,27,28,29]);
  print OUTPUT join ("  ",@vals), "\n";
  print unless ($a[22]) eq /^$/;
  chomp (@vals=@a[1,2,3,31,34,35,36]);
  print OUTPUT join ("  ",@vals), "\n";
  print unless ($a[28]) eq /^$/;
  chomp (@vals=@a[1,2,3,38,41,42,43]);
  print OUTPUT join ("  ",@vals), "\n";
  print unless ($a[34]) eq /^$/;
  chomp (@vals=@a[1,2,3,45,48,49,50]);
  print OUTPUT join ("  ",@vals), "\n";
  print unless ($a[40]) eq /^$/;
  chomp (@vals=@a[1,2,3,52,55,56,57]);
  print OUTPUT join ("  ",@vals), "\n";
  print unless ($a[46]) eq /^$/;
  chomp (@vals=@a[1,2,3,59,62,63,64]);
  print OUTPUT join ("  ",@vals), "\n";
  print unless ($a[52]) eq /^$/;
  close IN;
#  unlink $filename or die "Cannot delete $filename: $!";

I am getting:
10  30  2000  0-06-093195-7  1  9.05  9.05
10  30  2000  0-226-30784-0  1  9.30  9.30
10  30  2000  0-226-30780-8  1  19.25  19.25
10  30  2000  0-226-30792-1  1  29.30  29.30
10  30  2000  0-87220-390-5  1  229.25 229.25
10  30  2000       <====these are all blanks
10  30  2000       <====these are all blanks
10  30  2000       <====these are all blanks
10  30  2000       <====these are all blanks
10  30  2000       <====these are all blanks
10  30  2000
10  30  2000
10  30  2000     until it reaches the next record
10  30  2000  0-324-03301-X  1  8.25  8.25
10  30  2000
10  30  2000
10  30  2000

How do I perform a next unless a certain field has a value
or skip if there is no value in that field and go to the next record.

Also, the last two fields are numeric and can be 4, 5 or 6 characters
(dollar amounts)
but I want them right justified  as the final result    i.e.
10  30  2000  0-06-093195-7  1      9.05       9.05
10  30  2000  0-226-30784-0  1      9.30       9.30
10  30  2000  0-226-30780-8  1    19.25     19.25
10  30  2000  0-226-30792-1  1    29.30     29.30
10  30  2000  0-87220-390-5  1  229.25   229.25

should   printf    or   sprintf    come into play here and how


A Melton






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

Date: Tue, 14 Nov 2000 11:43:58 +1100
From: mgjv@tradingpost.com.au (Martien Verbruggen)
Subject: Re: Problem with chomp and print
Message-Id: <slrn9112md.gs3.mgjv@martien.heliotrope.home>

On Mon, 13 Nov 2000 23:44:00 GMT,
	Alan Melton <arm@home.com> wrote:
> By using this program:

You are not useing -w, and you are not using strict. Those two are
really, really valuable tools when debugging.

>   @a = <IN>; # read all lines of this file
>   chomp (@vals=@a[1,2,3,10,13,14,15]);
>   print OUTPUT join ("  ",@vals), "\n";
>   chomp (@vals=@a[1,2,3,17,20,21,22]);

Why don't you just chomp(@a) once, instead of repeatedly needing to do
it for the same components? Then you can just do something like:

print OUTPUT join("  ", @a[1,2,3,10,13,14,15]), "\n";

and you won't need the temporary @vals.

>   print OUTPUT join ("  ",@vals), "\n";
>   print unless $a eq /^$/;
                 ^^
                 Where did that come from?
                 What is it supposed to be?

Why the eq? Did you mean to match a pattern, or did you mean to check
that something was equal to something else? And what were those things?
And why are you printing to STDOUT suddenly? And what do you want to
print? You're actually printing the valeu of $_, whatever that is.

>   chomp (@vals=@a[1,2,3,24,27,28,29]);
>   print OUTPUT join ("  ",@vals), "\n";
>   print unless ($a[22]) eq /^$/;

print OUTPUT "something\n" unless $a[22] eq "";

>   chomp (@vals=@a[1,2,3,31,34,35,36]);
>   print OUTPUT join ("  ",@vals), "\n";
>   print unless ($a[28]) eq /^$/;
>   chomp (@vals=@a[1,2,3,38,41,42,43]);
>   print OUTPUT join ("  ",@vals), "\n";
>   print unless ($a[34]) eq /^$/;
>   chomp (@vals=@a[1,2,3,45,48,49,50]);
>   print OUTPUT join ("  ",@vals), "\n";
>   print unless ($a[40]) eq /^$/;
>   chomp (@vals=@a[1,2,3,52,55,56,57]);
>   print OUTPUT join ("  ",@vals), "\n";
>   print unless ($a[46]) eq /^$/;
>   chomp (@vals=@a[1,2,3,59,62,63,64]);
>   print OUTPUT join ("  ",@vals), "\n";
>   print unless ($a[52]) eq /^$/;

I only count 45 lines in your input. Your indexes are much larger than 44.

Why don't you just tell us what it is you're trying to do?

> How do I perform a next unless a certain field has a value

Is that what you are trying to do? Well, you do

next if $a[22] eq '';

or 

next unless $a[22] eq 'something';

but you'll have to be inside a loop. Are you?

Are you trying to figure out whether there was a line 45 before you use
it?

next unless @a >= 45;

> or skip if there is no value in that field and go to the next record.

What is a record? Was that input that we just saw a single record? if
so, where do the other records live, in other files? If so, you could
set up a loop

# warning, untested pseudo-code follows. Check, adapt and debug as
# needed

RECORD: 
foreach my $record (@records)
{
    open (REC, $record) or die "Cannot open record $record: $!";

    chomp(my @a = <REC>); # no more chomping needed after this

    # insert correct processing code here, one of the checks could be;

    next RECORD if @a <= 45;

    # more code

    close REC;
}

> Also, the last two fields are numeric and can be 4, 5 or 6 characters
> (dollar amounts)
> but I want them right justified  as the final result    i.e.
> 10  30  2000  0-06-093195-7  1      9.05       9.05
> 10  30  2000  0-226-30784-0  1      9.30       9.30
> 10  30  2000  0-226-30780-8  1    19.25     19.25
> 10  30  2000  0-226-30792-1  1    29.30     29.30
> 10  30  2000  0-87220-390-5  1  229.25   229.25

use a format, or use sprintf of printf. This is really what formats were
designed for. See the perlform documentation.

> should   printf    or   sprintf    come into play here and how

Yes, or no. I'd use a format in this particular case. But I can't be
much more specific, because I really don't know what you are trying to
do.

Martien
-- 
Martien Verbruggen              | 
Interactive Media Division      | Think of the average person. Half of
Commercial Dynamics Pty. Ltd.   | the people out there are dumber.
NSW, Australia                  | 


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

Date: Mon, 13 Nov 2000 23:49:18 GMT
From: David Steuber <nospam@david-steuber.com>
Subject: Re: Realrates.com needs your Rate and Salary Data!
Message-Id: <m3r94fjuv6.fsf@solo.david-steuber.com>

"Janet Ruhl" <ruhl@realrates.com> writes:

' I'm posting this message on the newsgroups where we've seen Realrates.com
' recommended as a resource over the past year.

I've missed all those recomendations.  This is only interesting
because I was recently seeking employment.

' By contributing your data, you ensure that this data is representative of
' the real salaries and rates received by real working computer professionals.

I don't think this is a scientifically valid method of gathering
statistical information.  You should be asking the employers what they
are paying.

There doesn't seem to be a question here for the dumb faq.  Heck, the
word "Perl" wasn't even mentioned in this post.

-- 
David Steuber | Perl apprentice.  The axe did not stop the
NRA Member    | mops and buckets from flooding my home.
ICQ# 91465842
***         http://www.david-steuber.com/          ***


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

Date: Mon, 13 Nov 2000 23:07:54 GMT
From: garry@ifr.zvolve.net (Garry Williams)
Subject: Re: Removing New Page character from a text file
Message-Id: <ev_P5.401$xb1.22292@eagle.america.net>

On Mon, 13 Nov 2000 15:51:13 -0600, Adnan <kilminjaroNOSPAM@hotmail.com> wrote:
>Hello,
>
> I have a text file that has newpage characters in it. If I do a 'more'
>or open the file using vi these characters show up as ^L. If I open the
>file using nedit editor these characters show up as <np>
>
> My question is, how can I get rid of these characters using a perl
>script?
>
>I have tried following but it doesnt work.
>
>#!/usr/local/bin/perl

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

>use strict;

This is a very good start.  

>my $file = 'myfilenamehere';
>open(FILE,"<$file") || die "Can't open `$file'! $!\n";

It's also excellent that you check the result of the open and print $!
in the error message.  

>while(<FILE>) {
>        if (m!\<np\>!) {
>                s/\<np\>//;
>        }
>        print;
>}
>
>Replacing <np> with ^L in the script didnt work either.

Well, I get the idea.  

First, there's no need to match for the character you want to squeeze
out (substitute) because the substitute does that anyway.  So you can
completely eliminate the if statement and concentrate on what to
substitute.  

Second, the `<' and `>' characters are not special in Perl regular
expressions, so there is no need to escape them.  

Third, That substitute will find the first occurrence of `<np>' and
replace it with a null string.  You said before that the thing you
really want to replace is a "newpage" character and you point out that
your text editor displays it as `^L'.  Well, that's a hint as to what
to use in the substitute.  The ^L is called a `control-L' and it is
the character that results when you hold down the control key and then
hit the L key.  So you really want to match for and replace (with a
null string) the control-L character.  

It is not at all obvious from either the perlop or perlre manual
pages, but both of them do make references to how to enter control
character sequences in quoted strings or match patterns.  What you
want is 

    while (<FILE>) {
	s/\cL//;
    }

As a matter of fact, that whole thing is easily done in a one-liner: 

    perl -pe 's/\cL//'

which will read on stdin and write translated results on stdout.  

By the way, another way to have done this would be to use the octal
sequence in your match pattern.  The way to find out what that would
be is to use your system's ascii manual page.  That will tell you that
a control-L or new-page is octal 014, so another way to say the same
pattern is

	s/\014//;

-- 
Garry Williams


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

Date: 14 Nov 2000 00:54:51 GMT
From: Hook's place <root@prettyfly.iinet.net.au>
Subject: sharing data between processes
Message-Id: <3a108d5b$0$30791@motown.iinet.net.au>

Got this problem ...

I've got a script which processes incoming packets and writes the
output to a database, and it works pretty well. However, I need to
make it more resilient, so I was considering splitting it into 2
parts :

	1.	read and process packets, write the data to a shared DBM file
	2.	another process reads the DBM file and updates the database

Sounds a bit odd perhaps, but the database may "disappear" for a while
from time to time, and the processed data has to be written chronologically.
Storing it locally within the existing process will work, but if the
database server isn't available for 10-15 minutes during high traffic
(due to network/hardware/software problems or whatever) there could be
a couple of thousand waiting updates, and they have to be done before
the new data gets written.

I feel (perhaps wrongly) that a second process handling the database
interface is a better solution. However, can a DBM file be shared
between 2 perl scripts such that one can write new records, and the
second can delete them?

The testing that I've done so far suggests not, and the perl books are
silent on the subject.

Is there a better solution (one which doesn't involve putting something
like mysql on the current server)?

The Hooker
--
"Do I look like a damned people person?"


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

Date: Tue, 14 Nov 2000 01:44:03 GMT
From: Bob Walton <bwalton@rochester.rr.com>
Subject: Re: sharing data between processes
Message-Id: <3A1099EE.64D7E2E1@rochester.rr.com>

Hook's place wrote:
> 
> Got this problem ...
> 
> I've got a script which processes incoming packets and writes the
> output to a database, and it works pretty well. However, I need to
> make it more resilient, so I was considering splitting it into 2
> parts :
> 
>         1.      read and process packets, write the data to a shared DBM file
>         2.      another process reads the DBM file and updates the database
> 
> Sounds a bit odd perhaps, but the database may "disappear" for a while
> from time to time, and the processed data has to be written chronologically.
> Storing it locally within the existing process will work, but if the
> database server isn't available for 10-15 minutes during high traffic
> (due to network/hardware/software problems or whatever) there could be
> a couple of thousand waiting updates, and they have to be done before
> the new data gets written.
> 
> I feel (perhaps wrongly) that a second process handling the database
> interface is a better solution. However, can a DBM file be shared
> between 2 perl scripts such that one can write new records, and the
> second can delete them?
Yes, that can work, but you've got to establish an exclusive cooperative
lock between the two processes that protects your dbm-type file from tie
to untie. See perldoc -f flock, perldoc -q lock.  Then carefully read
the docs your system provides about flock, fcntl, and anything else on
file locking you can get your hands on (that says whether or not it will
work across a network with your OS, for example).  My personal
recommendation is to ignore all that and set aside a zero-length file on
your local system strictly for keeping track of locking.  You can open
it for write (as is required for an exclusive lock on some systems)
without clobbering anything (because the file has no content), flock it,
do your protected stuff to your dbm-type file, and then close the lock
file's filehandle to release the lock.  This will all ensure that only
one process at a time can write to your dbm-type file, which is a
requirement for correct operation. I have processes in Perl similar to
yours that have been running glitch-free for many years using dbm-type
files with this form of locking. BTW, don't try any of that on Windoze
9x, as flock won't work (those OS's aren't real multitaskers in the
first place).  I don't know about Windoze ME or 2000.  Windoze NT
supports flock just fine.
> 
> The testing that I've done so far suggests not, and the perl books are
> silent on the subject.
> 
> Is there a better solution (one which doesn't involve putting something
> like mysql on the current server)?
> 
> The Hooker
 ...
-- 
Bob Walton


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

Date: Mon, 13 Nov 2000 23:50:57 GMT
From: David Steuber <nospam@david-steuber.com>
Subject: Re: Statistics for comp.lang.perl.misc
Message-Id: <m3n1f3jusg.fsf@solo.david-steuber.com>

Bart Lateur <bart.lateur@skynet.be> writes:

' Because of Abigail unorthodox way of quoting, he/she/it always got a
' very high value, simply because quoted text wasn't recognized as such.

I figure that's how I score so well in that category from time to
time.  Imagine!  I use a quote to quote text! ;-)

-- 
David Steuber | Perl apprentice.  The axe did not stop the
NRA Member    | mops and buckets from flooding my home.
ICQ# 91465842
***         http://www.david-steuber.com/          ***


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

Date: Mon, 13 Nov 2000 23:41:45 GMT
From: Alan Melton <arm@home.com>
Subject: writing on certain records in a file
Message-Id: <3A107B88.4420DD6F@home.com>

starting with a file as below

t-adam03@cougar.com
10
30
2000
46.15
2.65
2.50
51.30
Call
@
0-06-093195-7
STAFF
12499
1
9.05
9.05
ODYSSEY OF HOMER (TRANS LATTIMORE)(PERENNIAL (New)0-06-093195-7
0-226-30784-0
STAFF
12499
1
9.30
9.30
EURIPIDES V: THREE TRAGEDIES (P) (New)0-226-30784-0
0-226-30780-8
STAFF
12499
1
9.25
9.25
EURIPIDES I: FOUR TRAGEDIES (P) (New)0-226-30780-8
0-226-30792-1
STAFF
12499
1
9.30
9.30
SOPHOCLES I: THREE TRAGEDIES (P) (New)0-226-30792-1
0-87220-390-5
STAFF
ALL
1
9.25
9.25
ORESTEIA (TRANS MEINECK) (P) (New)0-87220-390-5


By using this program:

  @a = <IN>; # read all lines of this file
  chomp (@vals=@a[1,2,3,10,13,14,15]);
  print OUTPUT join ("  ",@vals), "\n";
  chomp (@vals=@a[1,2,3,17,20,21,22]);
  print OUTPUT join ("  ",@vals), "\n";
  print unless $a eq /^$/;
  chomp (@vals=@a[1,2,3,24,27,28,29]);
  print OUTPUT join ("  ",@vals), "\n";
  print unless ($a[22]) eq /^$/;
  chomp (@vals=@a[1,2,3,31,34,35,36]);
  print OUTPUT join ("  ",@vals), "\n";
  print unless ($a[28]) eq /^$/;
  chomp (@vals=@a[1,2,3,38,41,42,43]);
  print OUTPUT join ("  ",@vals), "\n";
  print unless ($a[34]) eq /^$/;
  chomp (@vals=@a[1,2,3,45,48,49,50]);
  print OUTPUT join ("  ",@vals), "\n";
  print unless ($a[40]) eq /^$/;
  chomp (@vals=@a[1,2,3,52,55,56,57]);
  print OUTPUT join ("  ",@vals), "\n";
  print unless ($a[46]) eq /^$/;
  chomp (@vals=@a[1,2,3,59,62,63,64]);
  print OUTPUT join ("  ",@vals), "\n";
  print unless ($a[52]) eq /^$/;
  close IN;
#  unlink $filename or die "Cannot delete $filename: $!";

I am getting:
10  30  2000  0-06-093195-7  1  9.05  9.05
10  30  2000  0-226-30784-0  1  9.30  9.30
10  30  2000  0-226-30780-8  1  19.25  19.25
10  30  2000  0-226-30792-1  1  29.30  29.30
10  30  2000  0-87220-390-5  1  229.25 229.25
10  30  2000       <====these are all blanks
10  30  2000       <====these are all blanks
10  30  2000       <====these are all blanks
10  30  2000       <====these are all blanks
10  30  2000       <====these are all blanks
10  30  2000
10  30  2000
10  30  2000     until it reaches the next record
10  30  2000  0-324-03301-X  1  8.25  8.25
10  30  2000
10  30  2000
10  30  2000

How do I perform a next unless a certain field has a value
or skip if there is no value in that field and go to the next record.

Also, the last two fields are numeric and can be 4, 5 or 6 characters
(dollar amounts)
but I want them right justified  as the final result    i.e.
10  30  2000  0-06-093195-7  1      9.05       9.05
10  30  2000  0-226-30784-0  1      9.30       9.30
10  30  2000  0-226-30780-8  1    19.25     19.25
10  30  2000  0-226-30792-1  1    29.30     29.30
10  30  2000  0-87220-390-5  1  229.25   229.25

A Melton




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

Date: 16 Sep 99 21:33:47 GMT (Last modified)
From: Perl-Users-Request@ruby.oce.orst.edu (Perl-Users-Digest Admin) 
Subject: Digest Administrivia (Last modified: 16 Sep 99)
Message-Id: <null>


Administrivia:

The Perl-Users Digest is a retransmission of the USENET newsgroup
comp.lang.perl.misc.  For subscription or unsubscription requests, send
the single line:

	subscribe perl-users
or:
	unsubscribe perl-users

to almanac@ruby.oce.orst.edu.  

| NOTE: The mail to news gateway, and thus the ability to submit articles
| through this service to the newsgroup, has been removed. I do not have
| time to individually vet each article to make sure that someone isn't
| abusing the service, and I no longer have any desire to waste my time
| dealing with the campus admins when some fool complains to them about an
| article that has come through the gateway instead of complaining
| to the source.

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 V9 Issue 4881
**************************************


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