[23301] in Perl-Users-Digest

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

Perl-Users Digest, Issue: 5521 Volume: 10

daemon@ATHENA.MIT.EDU (Perl-Users Digest)
Thu Sep 18 06:05:49 2003

Date: Thu, 18 Sep 2003 03:05:09 -0700 (PDT)
From: Perl-Users Digest <Perl-Users-Request@ruby.OCE.ORST.EDU>
To: Perl-Users@ruby.OCE.ORST.EDU (Perl-Users Digest)

Perl-Users Digest           Thu, 18 Sep 2003     Volume: 10 Number: 5521

Today's topics:
    Re: @_ in subroutine corrupts data? <ict@eh.org>
    Re: @_ in subroutine corrupts data? <rubyguru@hotmail.com>
    Re: A newBie Query <narendranath.ts@in.bosch.com>
    Re: Database Record into a hash... <ThomasKratz@REMOVEwebCAPS.de>
    Re: I know I can do this with a regex, but... (Anno Siegel)
    Re: I know I can do this with a regex, but... <abigail@abigail.nl>
        list-parsing problem (Marcus Claesson)
    Re: list-parsing problem <peter@semantico.com>
    Re: list-parsing problem (Anno Siegel)
    Re: list-parsing problem <ak+usenet@freeshell.org>
    Re: list-parsing problem <kasp@epatra.com>
    Re: OT:  WebGUI, any reviews? <bart.lateur@pandora.be>
    Re: Outlook Address Books and Perl? <jwillmore@cyberia.com>
    Re: Outlook Address Books and Perl? <nmihai_2000@yahoo.com>
    Re: Outlook Address Books and Perl? (Villy Kruse)
    Re: package problem? [was Re: @_ in subroutine corrupts <sholden@staff.cs.usyd.edu.au>
    Re: package problem? [was Re: @_ in subroutine corrupts <rubyguru@hotmail.com>
        quick and dirty shell vs elegant perl (Phil Meyer)
    Re: quick and dirty shell vs elegant perl <tassilo.parseval@rwth-aachen.de>
    Re: Quoting "$vars" and open() (Chris Marshall)
    Re: Quoting "$vars" and open() (Chris Marshall)
    Re: Quoting "$vars" and open() (Chris Marshall)
    Re: Quoting "$vars" and open() (Sam Holden)
    Re: string to integer <bart.lateur@pandora.be>
    Re: tar gone wild under perl <kalinabears@iinet.net.au>
        wtf is the deal? <tom@nosleep.net>
    Re: wtf is the deal? <uri@stemsystems.com>
    Re: wtf is the deal? <tom@nosleep.net>
    Re: wtf is the deal? <tom@nosleep.net>
    Re: wtf is the deal? <uri@stemsystems.com>
    Re: wtf is the deal? <tom@nosleep.net>
    Re:  <bwalton@rochester.rr.com>
        Digest Administrivia (Last modified: 6 Apr 01) (Perl-Users-Digest Admin)

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

Date: 18 Sep 2003 14:27:49 +1000
From: Iain Truskett <ict@eh.org>
Subject: Re: @_ in subroutine corrupts data?
Message-Id: <slrnbmidgq.lf2.ict@dellah.org>

* synthespian <synthespian@uol.com.br>:


[...]
> So this is about context, is it? $_ will be the placeholder for an
> array indexed when $array[$_], otherwise it is not 0-indexed, that is,
> is $_ in the case of print "$_\n" evaluating to the number of
> elements?  Or is it a placeholder for the /elements/ themselves?

> What's up with this (perceived) inconsistency?

There's no inconsistency. In a loop such as:

    foreach (@array) {
       ...
    }

$_ is set to each element of the array in turn. At no point does $_
contain an array index or the array size except by mathematical
coincidence (that is, the numbers happen to be the same).

The following code should illustrate the point (yes, it's mostly your
code, I just tweaked what it prints and declared some variables and give
it different input):

    #!/usr/bin/perl
    my @words = subthis( "hello", "xyzzy", "plugh" );

    sub subthis {
        my @array = @_;
        foreach (@array) {
            print "$_\n";
        }
        return @array;
    }



cheers,
-- 
Iain.


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

Date: Thu, 18 Sep 2003 04:55:07 GMT
From: "Chris Dutton" <rubyguru@hotmail.com>
Subject: Re: @_ in subroutine corrupts data?
Message-Id: <LUaab.9252$CU3.785@pd7tw3no>

"synthespian" <synthespian@uol.com.br> wrote in message
news:bkb8j5$rjcqj$1@ID-78052.news.uni-berlin.de...
>   Yes, it's obvious! Thanks to you and Chris Dutton for taking the time.
>   I thought that what would be set to $_ was the /number/ of elements in
> @array, and not 1, 2, 3, 4, and that this number would start at 0.

To get the number of elements in an array, assign it to a scalar, like so:

my @someArray = (1,2,3,4);
my $lengthOfArray = @someArray;
print "$lengthOfArray\n";
# prints:
# 4

>   So this is about context, is it? $_ will be the placeholder for an
> array indexed when $array[$_], otherwise it is not 0-indexed, that is,
> is $_ in the case of print "$_\n" evaluating to the number of elements?
> Or is it a placeholder for the /elements/ themselves?

$_ is just a helpful timesaver.  It can be a shortcut in that many of Perl's
built-ins use it if no argument is provided.  For instance, "print;" is
equivalent to "print $_;".

In the foreach loop, $_ serves as a shortcut to each element of the array.
This can be easily replaced with a more meaningful name if your goal is
long-term maintainability.

foreach (@foo) { print }

is equivalent to:

foreach my $item (@foo) { print $item }


---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.512 / Virus Database: 309 - Release Date: 8/19/2003




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

Date: Thu, 18 Sep 2003 14:20:57 +0530
From: "Naren" <narendranath.ts@in.bosch.com>
Subject: Re: A newBie Query
Message-Id: <bkbrm2$2ve$1@ns2.fe.internet.bosch.com>

Hello Grp,
        Thanks for all the suggestions and advices.I could do the required
functionality.I shall  specify the problems in a detailed manner in future.

Thanks again

Rgds,
Naren.




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

Date: Thu, 18 Sep 2003 11:22:47 +0200
From: "Thomas Kratz" <ThomasKratz@REMOVEwebCAPS.de>
Subject: Re: Database Record into a hash...
Message-Id: <3f6979ef.0@juno.wiesbaden.netsurf.de>


"Donavon" <djlerman@yahoo.com> wrote in
news:97ba267a.0309171038.79aeef1e@posting.google.com...
> I am trying to load a database into a HASH of HASH.  For some
reason
> every instance of the HASH only contains the data from the last
record
> pulled?
>
> So I have a 1000 copies of the same information with different
HASH
> keys.
> Any suggestions??
>
> ...
> ...
> ...
> # loads a record into a hash
> while ($data = $sth->fetchrow_hashref) {

while (my $data = $sth->fetchrow_hashref) {
# create a new hashref for each loop

>
> %record = %$data;

delete the above line, you do not need a temporary hash.

> $key = $record{'ProjectNumber'};
> $hash{$key} = \%record;

$hash{$data->{'ProjectNumber'}} = $data;

>
> };
>
> $sth -> finish;

A more elegant alternative is:

my $hashref;
unless ( $hashref = $sth->fetchall_hashref('ProjectNumber') ) {
   warn "couldn't fetch data, $DBI::errstr\n";
}
# let DBI do the loop and create the hash
# no need to call $sth->finish() now

> $dbh -> disconnect
> or warn "Disconnection failed: $DBI::errstr\n";
>
> # prints out content of HASH
> foreach $key1 (keys %hash) {

foreach $key1 (keys %$hashref) {

> print 'Level 1: ' . $key1 . "<BR>";
>
> foreach $key2 (keys %{$hash{$key1}}) {
> print $key2 . '=>' . $hash{$key1}{$key2} . "<BR>";

foreach $key2 (keys %{$hashref->{$key1}}) {
   print $key2 . '=>' . $hashref->{$key1}{$key2} . "<BR>";

> };
> };

(untested, more in 'perldoc DBI')

Thomas




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

Date: 18 Sep 2003 08:46:52 GMT
From: anno4000@lublin.zrz.tu-berlin.de (Anno Siegel)
Subject: Re: I know I can do this with a regex, but...
Message-Id: <bkbrds$o08$1@mamenchi.zrz.TU-Berlin.DE>

Tman <nerdy1@snet.net> wrote in comp.lang.perl.misc:
> Need to strip comments from VBScript code.
> 
> Tried to use a state machine to tell if I was in quotes, but got very
> confused.  I know I can use a regex, although I may have to call it
> repeatedly to eat quoted strings.  Anyone have ideas?
> 
> I need to whack everything after the first comment character...
> 
> this is not a comment
> 'this line is fully commented
> the comment 'in this line starts after ' the word comment
> there "is no 'comment" in this line
> but in "this 'line" there 'is a "comment" before the word "is"
> 'this line is "fully" commented

Take a look at Regex::Common.  It has elaborate regexes that deal
with comments.

Anno


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

Date: 18 Sep 2003 09:39:58 GMT
From: Abigail <abigail@abigail.nl>
Subject: Re: I know I can do this with a regex, but...
Message-Id: <slrnbmivbd.gei.abigail@alexandra.abigail.nl>

Anno Siegel (anno4000@lublin.zrz.tu-berlin.de) wrote on MMMDCLXX
September MCMXCIII in <URL:news:bkbrds$o08$1@mamenchi.zrz.TU-Berlin.DE>:
^^  Tman <nerdy1@snet.net> wrote in comp.lang.perl.misc:
^^ > Need to strip comments from VBScript code.
^^ > 
^^ > Tried to use a state machine to tell if I was in quotes, but got very
^^ > confused.  I know I can use a regex, although I may have to call it
^^ > repeatedly to eat quoted strings.  Anyone have ideas?
^^ > 
^^ > I need to whack everything after the first comment character...
^^ > 
^^ > this is not a comment
^^ > 'this line is fully commented
^^ > the comment 'in this line starts after ' the word comment
^^ > there "is no 'comment" in this line
^^ > but in "this 'line" there 'is a "comment" before the word "is"
^^ > 'this line is "fully" commented
^^  
^^  Take a look at Regex::Common.  It has elaborate regexes that deal
^^  with comments.


But Regexp::Common will only give you patterns for comments - it 
doesn't include language parsers. All the patterns of Regexp::Common
are context free - but for most languages the pattern for comments
isn't context free (for instance, they can be included in literals).

Having said that, if the only concern is double quoted strings,
something like this might work (untested):

    use Regexp::Common;

    s [($RE{delimited}{-delim => '"'})|'.*\n]
      [$1 || ""]eg;


Abigail
-- 
perl -weprint\<\<EOT\; -eJust -eanother -ePerl -eHacker -eEOT


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

Date: 18 Sep 2003 02:19:52 -0700
From: m.claesson@student.ucc.ie (Marcus Claesson)
Subject: list-parsing problem
Message-Id: <e818c15b.0309180119.47e7d9c9@posting.google.com>

Hi People,

I have a silly little list-parsing problem that I can't get my head
around, and I'm sure some of you have come across it before.

I have a list like this:

1	a
2	b
2	c
3	a
4	d
4	d
4	e
4	f
5	g

and I want to make the first column non-redundant and collect the
second column values on the same line, like this:

1	a
2	b,c
3	a
4	d,e,f
5	g

Please note that line 4 only has one 'd'.

I've tried with both hashes and arrays (don't want to confuse you so I
won't display them here), but nothing really works...

I would really appreciate any help!

Marcus


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

Date: Thu, 18 Sep 2003 10:40:15 +0100
From: Peter Hickman <peter@semantico.com>
Subject: Re: list-parsing problem
Message-Id: <3f697d83$0$24111$afc38c87@news.easynet.co.uk>

Marcus Claesson wrote:
> Hi People,
> 
> I have a silly little list-parsing problem that I can't get my head
> around, and I'm sure some of you have come across it before.
> 
> I have a list like this:
> 
> 1	a
> 2	b
> 2	c
> 3	a
> 4	d
> 4	d
> 4	e
> 4	f
> 5	g
> 
> and I want to make the first column non-redundant and collect the
> second column values on the same line, like this:
> 
> 1	a
> 2	b,c
> 3	a
> 4	d,e,f
> 5	g
> 
> Please note that line 4 only has one 'd'.
> 
> I've tried with both hashes and arrays (don't want to confuse you so I
> won't display them here), but nothing really works...
> 
> I would really appreciate any help!
> 
> Marcus

Build up a hash of hashes

For each data pair...

$data{$left}->{$right}=1;

Then report by...

foreach my $key (keys %data) {
	print "$key\t";
	print join(',', keys %{$data{$key}});
	print "\n";
}

Ok could be better but I am only on my first cup of tea.



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

Date: 18 Sep 2003 09:47:00 GMT
From: anno4000@lublin.zrz.tu-berlin.de (Anno Siegel)
Subject: Re: list-parsing problem
Message-Id: <bkbuuk$qah$1@mamenchi.zrz.TU-Berlin.DE>

Marcus Claesson <m.claesson@student.ucc.ie> wrote in comp.lang.perl.misc:
> Hi People,
> 
> I have a silly little list-parsing problem that I can't get my head
> around, and I'm sure some of you have come across it before.
> 
> I have a list like this:
> 
> 1	a
> 2	b
> 2	c
> 3	a
> 4	d
> 4	d
> 4	e
> 4	f
> 5	g
> 
> and I want to make the first column non-redundant and collect the
> second column values on the same line, like this:
> 
> 1	a
> 2	b,c
> 3	a
> 4	d,e,f
> 5	g
> 
> Please note that line 4 only has one 'd'.
> 
> I've tried with both hashes and arrays (don't want to confuse you so I
> won't display them here), but nothing really works...

As usual, when uniqueness and duplicates come into play, the Perl
solution involves a hash.  In your problem, you want to eliminate
two kinds of duplicates, so we shall need to us the hash trick twice.

First, make the numbers in the first column hash keys that will
eventually point to the list of letters associated with it.  That
will bring multiple numbers together.

First off, we create hash(ref)s for each of the numbers, whose keys
will be the letters associated with each number.  That will store
each letter only once for a number.

When all the letters have been collected, we transform the hashes to
lists of their keys.  Finally, print the result.  In code:

    my %coll;
    while ( <DATA> ) {
        my ( $first, $second) = split;
        undef $coll{ $first}->{ $second}; # undef brings the key to existence
    }

    # replace hashes with lists of keys
    $_ = [ sort keys %$_ ] for values %coll;

    # print result
    for ( sort keys %coll ) {
        print "$_ -> @{ $coll{ $_}}\n"
    }

    __DATA__
    1       a
    2       b
    2       c
    3       a
    4       d
    4       d
    4       e
    4       f
    5       g

If the sequence of the numbers or letters doesn't matter, take out
the relevant "sort".

Anno


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

Date: Thu, 18 Sep 2003 09:48:42 +0000 (UTC)
From: Andreas Kahari <ak+usenet@freeshell.org>
Subject: Re: list-parsing problem
Message-Id: <slrnbmivrp.8sg.ak+usenet@vinland.freeshell.org>

In article <e818c15b.0309180119.47e7d9c9@posting.google.com>,
Marcus Claesson wrote:
> Hi People,
> 
> I have a silly little list-parsing problem that I can't get my head
> around, and I'm sure some of you have come across it before.
> 
> I have a list like this:
[cut]
> 
> and I want to make the first column non-redundant and collect the
> second column values on the same line, like this:
[cut]
> 
> Please note that line 4 only has one 'd'.
> 
> I've tried with both hashes and arrays (don't want to confuse you so I
> won't display them here), but nothing really works...
> 
> I would really appreciate any help!

One, possibly suboptimal, way of doing it:


my %hash;
while (defined(my $line = <>)) {
    chomp $line;
    my @fields = split /\s+/, $line;
    $hash{$fields[0]}{$fields[1]} = 1; # Note its precence
}

while (my ($key, $val) = each %hash) {
    printf "%s\t%s\n", $key, join(',', keys %{ $val });
}

No error handling...

-- 
Andreas Kähäri


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

Date: Thu, 18 Sep 2003 15:22:22 +0530
From: "Kasp" <kasp@epatra.com>
Subject: Re: list-parsing problem
Message-Id: <bkbvjc$lgt$1@newsreader.mailgate.org>

ALGORITHM: (Since you know hashes and array, here are the steps to get what
you want)
1. Read input (eg. 1 a )
2. Check if an element with key = 1 exists
3. If it does not exist, add the key 1 and it's value as 'a'. Go to step 1
and read next input
4. If it exists, check in hash's correspoding value to see if a exists
already. If it does do nothing....go to step 1 and read next input.
   If the hash's value does not contain the character 'a'...append a comman
followed by a 'a'.
Eg. if ($hash{'1'} !~ m/a/) then $hash{'1'}= $hash{'1'}.'a'

Hope you get the idea.

-- 
"Accept that some days you are the pigeon and some days the statue."
"A pat on the back is only a few inches from a kick in the butt." - Dilbert.




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

Date: Thu, 18 Sep 2003 06:32:05 GMT
From: Bart Lateur <bart.lateur@pandora.be>
Subject: Re: OT:  WebGUI, any reviews?
Message-Id: <s8kimv0rcmgj7kcati32bol2c7eqju6ou1@4ax.com>

Dan Wilga wrote:

>Last I checked, the source code is available. Why not download it and 
>try it for yourself?

So everybody's a security expert now, are they?

-- 
	Bart.


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

Date: Thu, 18 Sep 2003 06:25:58 GMT
From: James Willmore <jwillmore@cyberia.com>
Subject: Re: Outlook Address Books and Perl?
Message-Id: <20030918022614.6e0acf49.jwillmore@cyberia.com>

On Tue, 16 Sep 2003 10:05:54 -0700
"Mark" <nospam@thanksanyway.org> wrote:
> Yes, but the several Perl modules that "read" an OE
> address book, actually require that the data be exported
> from OE first. OE only exports its address book as
> comma-separated values (*.CSV). Unfortunately, this is
> a useless format, since data fields in the OE address book
> fields can (and often will) contain commas. The output
> cannot be parsed reliably.
> 
> So I was hoping for a Perl module that can actually read
> the OE address book's binary format directly.

Ah ... well, you could examine the exported OE file in a hex editor to
see if M$ put in some hidden characters.  Or, you could see if the
file follows a pattern and then code for that pattern (think pack or
regular expression).

All of these suggestions are based on  opinion based upon some
experience with other files that needed parsing.  It _may_ look like a
CSV file, but is it _really_ a CSV file?  Is it something that, when 
looked at from a fresh perspective, something that can be parsed?

HTH

-- 
Jim

Copyright notice: all code written by the author in this post is
 released under the GPL. http://www.gnu.org/licenses/gpl.txt 
for more information.

a fortune quote ...
If it's Tuesday, this must be someone else's fortune. 



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

Date: Thu, 18 Sep 2003 06:52:36 GMT
From: "Mihai N." <nmihai_2000@yahoo.com>
Subject: Re: Outlook Address Books and Perl?
Message-Id: <Xns93F9F2E76D71AMihaiN@63.240.76.16>

> So I was hoping for a Perl module that can actually read
> the OE address book's binary format directly.
I'm afraid the only decent solution is OLE.

Mihai


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

Date: 18 Sep 2003 07:31:06 GMT
From: vek@station02.ohout.pharmapartners.nl (Villy Kruse)
Subject: Re: Outlook Address Books and Perl?
Message-Id: <slrnbminpd.8in.vek@station02.ohout.pharmapartners.nl>

On Tue, 16 Sep 2003 10:05:54 -0700,
    Mark <nospam@thanksanyway.org> wrote:


>
>"James Willmore" <jwillmore@cyberia.com> wrote:
>> http://search.cpan.org/
>> search keyword: outlook
>>
>> first item thats shows is: mbx2mbox
>
>Yes, but the several Perl modules that "read" an OE
>address book, actually require that the data be exported
>from OE first. OE only exports its address book as
>comma-separated values (*.CSV). Unfortunately, this is
>a useless format, since data fields in the OE address book
>fields can (and often will) contain commas. The output
>cannot be parsed reliably.
>


Not even with Text::ParseWords?  It is my understanding that
Text::Parsewords will deal with occurrences of the separator character
within quoted strings.



Villy


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

Date: 18 Sep 2003 04:23:13 GMT
From: Sam Holden <sholden@staff.cs.usyd.edu.au>
Subject: Re: package problem? [was Re: @_ in subroutine corrupts data?]
Message-Id: <slrnbmicph.qgp.sholden@staff.cs.usyd.edu.au>

On Thu, 18 Sep 2003 00:41:30 -0300, synthespian <synthespian@uol.com.br> wrote:
> While we're on this, it got weird with "strict" and "warnings". Why?

perldoc strict

> 
> 
> @arrayb = subthat(1, 2, 3, 4);
> 
> sub subthat {
>      @arrayb = @_;
>      foreach (@arrayb) {
>          print "$_\n";
>      }
> }
> 
> print "Finished\n";
> 
> $ perl subrout3.pl
> Global symbol "@arrayb" requires explicit package name at subrout3.pl 
> line 5.
> Global symbol "@arrayb" requires explicit package name at subrout3.pl 
> line 9.
> Global symbol "@arrayb" requires explicit package name at subrout3.pl 
> line 10.
> Execution of subrout3.pl aborted due to compilation errors.


The section marked "strict vars" is the relevant bit.

-- 
Sam Holden



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

Date: Thu, 18 Sep 2003 04:43:20 GMT
From: "Chris Dutton" <rubyguru@hotmail.com>
Subject: Re: package problem? [was Re: @_ in subroutine corrupts data?]
Message-Id: <IJaab.2320$8D4.94@pd7tw1no>

"synthespian" <synthespian@uol.com.br> wrote in message
news:bkb9kv$qum8m$1@ID-78052.news.uni-berlin.de...
> While we're on this, it got weird with "strict" and "warnings". Why?
>
>
> @arrayb = subthat(1, 2, 3, 4);
>
> sub subthat {
>      @arrayb = @_;
>      foreach (@arrayb) {
>          print "$_\n";
>      }
> }
>
> print "Finished\n";
>
> $ perl subrout3.pl
> Global symbol "@arrayb" requires explicit package name at subrout3.pl
> line 5.

As I mentioned in my earlier reply, when you assign to @arrayb in your
subroutine, you're not automatically creating a new array.  Rather you're
assigning to the @arrayb that's already in the "main" package.  Now, while
you can do this, it's not advisable since you can get unexpected results.

You can use the "my" keyword to create a new array inside the subroutine
which has the same name as one in the outer scope.

@arrayb = subthat(1, 2, 3, 4);

sub subthat {
     my @arrayb = @_;
     foreach (@arrayb) {
         print "$_\n";
     }
     # and I presume from your previous subroutine,
     # and how this one is used, that you want @arrayb
     # returned.
     return @arrayb;
}





---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.512 / Virus Database: 309 - Release Date: 8/19/2003




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

Date: 18 Sep 2003 05:58:50 GMT
From: x0pmeyer@ti.com (Phil Meyer)
Subject: quick and dirty shell vs elegant perl
Message-Id: <bkbhiq$9dh$1@home.itg.ti.com>

Part of the objective is to find a reliable way to discover the qlogic fiber
channel card WWN and which WWN(s) it connects to.  This data is then stored
and compared to WWN data from the SAN fabric to determine which switch port
its connected to, and also which storage devices it is talking to.

Assumptions: Solaris systems, and explorer output as only source.

All of that aside, this is indeed a generic type issue, ie:  is it ever
'better' to jump out to the shell for a quick and dirty, vs learning the
'better way' in perl.  Honestly, this may be embarrassing to me, but it
is troublesome to look at a problem and have my mind see hundreds of lines
of perl code, or a few simple lines of shell commands.

OK here is the detail:  The filenames are consistant and start with
	luxadm_display_
There can be over 34,000 lines returned.

The function here is pretty self contained, so that this should be a
pretty clear example.  And this style of C programming was fashionable
before most of you were born, so please try to limit the comments about
where curlies go.  Thanks!

#!/usr/bin/perl -w

$ENV{'ORACLE_HOME'} = "/oracle/product/8.1.7a";

use File::stat qw(:FIELDS);
use DBI;
use strict;


get_WWN_sun()
        {
        my $cmd = "";
        my $g = "";
        my @data = "";
        my $lun = "";
        my $host_port = "";
        my $i = 0 ;
        my $line = "";
	my $loc = "/export/data/explorer/blah_blah_blah/disks/luxadm_display*";

# This is the code in question -- How do do this as well in perl
# grep each half into seperate files, then paste them together.

        $cmd = "grep -h \"LUN path port WWN\" $loc > /tmp/LUNs";
        @data = system($cmd);
        $cmd = "grep -h \"Host controller port WWN\" $loc > /tmp/Hosts";
        @data = system($cmd);
        $cmd = "paste /tmp/LUNs /tmp/Hosts | sort -u";
        @data = `$cmd`;

# At this point I have boilded thousands of lines of data to just a couple.
# what is the better way?
# From here down is just database stuff, and yes it would be better to
# bind the variables, but the data is known and there are never special chars
# db connections are global

        for ( @data )
                {
                ($g,$g,$g,$g,$lun,$g,$g,$g,$g,$host_port) = split();
                $line = "SELECT count(*) from WWN where
                                system like \'$host\' and
                                lun like \'$lun\'";
                $i = $dbh->selectrow_array($line);
                if ( $i == 0 )
                        {
                        $line = "INSERT INTO WWN VALUES
                                ( \'$host\',\'$lun\',\'$host_port\',\'\',\'$drvr\',\'\' )";
                        print $line;
                        $sth0 = $dbh->prepare($line);
                        $sth0->execute();
                        }
                else
                        {
                        $line = "UPDATE WWN SET
                                host_port = \'$host_port\',
                                driver = \'$drvr\'
                                where
                                        system = \'$host\' and
                                        lun = \'$lun\'";
                        print $line;
                        $sth0 = $dbh->prepare($line);
                        $sth0->execute();
                        }
                }
        }




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

Date: 18 Sep 2003 08:46:21 GMT
From: "Tassilo v. Parseval" <tassilo.parseval@rwth-aachen.de>
Subject: Re: quick and dirty shell vs elegant perl
Message-Id: <bkbrct$e3i$1@nets3.rz.RWTH-Aachen.DE>

Also sprach Phil Meyer:

> Part of the objective is to find a reliable way to discover the qlogic fiber
> channel card WWN and which WWN(s) it connects to.  This data is then stored
> and compared to WWN data from the SAN fabric to determine which switch port
> its connected to, and also which storage devices it is talking to.
> 
> Assumptions: Solaris systems, and explorer output as only source.
> 
> All of that aside, this is indeed a generic type issue, ie:  is it ever
> 'better' to jump out to the shell for a quick and dirty, vs learning the
> 'better way' in perl.  Honestly, this may be embarrassing to me, but it
> is troublesome to look at a problem and have my mind see hundreds of lines
> of perl code, or a few simple lines of shell commands.

It really depends. Your script is a typical system-admin's script.
Things like portability between platforms, beauty etc. aren't a concern
in these cases. I also have a couple of such scripts: No beauty-award
for them, but they get their job done.

If you find that a problem can be solved more quickly using external
tools, then do so.

> OK here is the detail:  The filenames are consistant and start with
> 	luxadm_display_
> There can be over 34,000 lines returned.
> 
> The function here is pretty self contained, so that this should be a
> pretty clear example.  And this style of C programming was fashionable
> before most of you were born, so please try to limit the comments about
> where curlies go.  Thanks!

:-) Ok.

> #!/usr/bin/perl -w
> 
> $ENV{'ORACLE_HOME'} = "/oracle/product/8.1.7a";
> 
> use File::stat qw(:FIELDS);
> use DBI;
> use strict;
> 
> 
> get_WWN_sun()
>         {
>         my $cmd = "";
>         my $g = "";
>         my @data = "";
>         my $lun = "";
>         my $host_port = "";
>         my $i = 0 ;
>         my $line = "";
> 	my $loc = "/export/data/explorer/blah_blah_blah/disks/luxadm_display*";
> 
> # This is the code in question -- How do do this as well in perl
> # grep each half into seperate files, then paste them together.
> 
>         $cmd = "grep -h \"LUN path port WWN\" $loc > /tmp/LUNs";
>         @data = system($cmd);
>         $cmd = "grep -h \"Host controller port WWN\" $loc > /tmp/Hosts";
>         @data = system($cmd);
>         $cmd = "paste /tmp/LUNs /tmp/Hosts | sort -u";
>         @data = `$cmd`;

The above code suggests that system(COMMAND) actually returns the output
of a command. It doesn't. It returns a success- (or failure-) code. See
'perldoc -f system'. Backticks can be used to capture the output (as you
demonstrated in the last line of the above).

Doing the above in Perl could look like this [untested]:

    my %lines;      # used to make lines unique
    local @ARGV = </export/data/explorer/blah_blah_blah/disks/luxadm_display*>;
    local $_;       # just in case
    while (<>) {
        chomp;
        $lines{ $_ } if index($_, "Host controller port WWN") != -1 or
                        index($_, "LUN path port WWN" != -1;
    }
    my @data = sort keys %seen;
        
This already uses a few short-cuts, like employing glob() in order to
avoid a tedious opendir/readdir/grep combination to select the right
files. Then it assigns them to @ARGV so that we don't have to open them
and can just iterate over the special empty file-handle (<>).

Filling the matching lines into a hash ensures that they are unique. I
used index because it may be slightly quicker than a fullblown regex.
Your grep pattern is just a string so index() works fine for that.
Finally we just sort the keys and assign them to @data. 

> # At this point I have boilded thousands of lines of data to just a couple.
> # what is the better way?
> # From here down is just database stuff, and yes it would be better to
> # bind the variables, but the data is known and there are never special chars
> # db connections are global
> 
>         for ( @data )
>                 {
>                 ($g,$g,$g,$g,$lun,$g,$g,$g,$g,$host_port) = split();

You only want two values, so use a list-slice here:

    my ($lun, $host_port) = (split)[4,9];

>                 $line = "SELECT count(*) from WWN where
>                                 system like \'$host\' and
>                                 lun like \'$lun\'";
>                 $i = $dbh->selectrow_array($line);

Here you should better be using DBI's quoting features:

    my $sth = $dbh->prepare(<<EOS);
    SELECT count(*) from WWN where system like ? and lun like ?
    EOS
    $sth->execute($host, $lun);
    # now use $sth->fetchrow_array or so to retrieve the results

The advantage of this is that the quoting will be done for you. But
depending on the values that can be in $host and $lun there might not be
any quoting needed.

[...]

Tassilo
-- 
$_=q#",}])!JAPH!qq(tsuJ[{@"tnirp}3..0}_$;//::niam/s~=)]3[))_$-3(rellac(=_$({
pam{rekcahbus})(rekcah{lrePbus})(lreP{rehtonabus})!JAPH!qq(rehtona{tsuJbus#;
$_=reverse,s+(?<=sub).+q#q!'"qq.\t$&."'!#+sexisexiixesixeseg;y~\n~~dddd;eval


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

Date: 17 Sep 2003 23:43:41 -0700
From: c_j_marshall@hotmail.com (Chris Marshall)
Subject: Re: Quoting "$vars" and open()
Message-Id: <cb9c7b76.0309172243.4c8b77c7@posting.google.com>

Andreas> open(DATA, ">" . $var) or die;	# Writing

Tad> This is not related to the current discussion.
Andreas> Hmm...  I must have misread the question.  How do you
interpret
Andreas> the question?

Tad> I thought he was asking about the Perl FAQ above.


I guess that Andreas was "right" in interpreting my question - I was
hoping to come away with what he gave me:

open(DATA, $var) or die; # Reading

open(DATA, ">" . $var) or die; # Writing


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

Date: 17 Sep 2003 23:44:20 -0700
From: c_j_marshall@hotmail.com (Chris Marshall)
Subject: Re: Quoting "$vars" and open()
Message-Id: <cb9c7b76.0309172244.2e9b913f@posting.google.com>

Andreas Kahari <ak+usenet@freeshell.org> wrote in message news:<slrnbmgqce.cru.ak+usenet@vinland.freeshell.org>...
> In article <cb9c7b76.0309170556.5bac0a80@posting.google.com>,
> Chris Marshall wrote:
> > I know its wrong to quote "$vars" - but is there an easy way around it
> > when using open() and your filename is in a $var ?
> 
> I wouldn't say it's "wrong", but it's easy to avoid:
> 
> open(DATA, $var) or die;	# Reading
> 
> open(DATA, ">" . $var) or die;	# Writing


Just what I was looking for - thanks.


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

Date: 17 Sep 2003 23:54:18 -0700
From: c_j_marshall@hotmail.com (Chris Marshall)
Subject: Re: Quoting "$vars" and open()
Message-Id: <cb9c7b76.0309172254.23615a0f@posting.google.com>

tadmc@augustmail.com (Tad McClellan) wrote in message news:<slrnbmgsjg.7o0.tadmc@magna.augustmail.com>...
> Chris Marshall <c_j_marshall@hotmail.com> wrote:
> 
> > I know its wrong to quote "$vars" - but is there an easy way around it
> 
> 
> Yes:
> 
>    Delete the double quote characters!


How about when using open() to write to a file. e.g.

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

my $var = "file.txt";

open(DATA, > $var) or die "$!"; # Writing
print DATA "hello world\n";


 ./test.pl
syntax error at test.pl line 7, near ", >"
Execution of test.pl aborted due to compilation errors.


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

Date: 18 Sep 2003 09:39:41 GMT
From: sholden@flexal.cs.usyd.edu.au (Sam Holden)
Subject: Re: Quoting "$vars" and open()
Message-Id: <slrnbmivat.u0o.sholden@flexal.cs.usyd.edu.au>

On 17 Sep 2003 23:54:18 -0700, Chris Marshall <c_j_marshall@hotmail.com> wrote:
> tadmc@augustmail.com (Tad McClellan) wrote in message news:<slrnbmgsjg.7o0.tadmc@magna.augustmail.com>...
>> Chris Marshall <c_j_marshall@hotmail.com> wrote:
>> 
>> > I know its wrong to quote "$vars" - but is there an easy way around it
>> 
>> 
>> Yes:
>> 
>>    Delete the double quote characters!
> 
> 
> How about when using open() to write to a file. e.g.

Then you use quotes obviously, since it is a completely different case.

">$vars" is completely different than "$vars".

[snip silly example]

-- 
Sam Holden



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

Date: Thu, 18 Sep 2003 06:43:27 GMT
From: Bart Lateur <bart.lateur@pandora.be>
Subject: Re: string to integer
Message-Id: <kgkimvk1epv71v2idh8q61tp5suf5lodmq@4ax.com>

Mark Fenbers wrote:

>hex($val) instead of int($val)...
>
>This solves my problem partially, but I was actually hoping for a solution to
>accept either hex or decimal formats (e.g., 0xff or 255).  If there is none, I
>can add a few lines of code to test for '0x' and use hex() if found...

I'd also like to point towards oct(). By contrast, oct() is a little
smarter, it can do not just octal, but binary and hex conversions too,
with the proper letter flag. So my test would be:

	$int = $val =~ /^0/ ? oct($val) : 0+$val;

You can try it with "123", "0177" (=127), "0xFF" (=255) and "0b1101"
(=13), for example:

    foreach my $val (qw(123 0177 0xFF 0b1101)) {
        printf "'%s' is %d\n", $val, $val =~ /^0/ ? oct($val) : 0+$val;
    }

This simple test will only work for integers, though: "0.123" isn't
supposed to be treated as octal.

-- 
	Bart.


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

Date: Wed, 10 Sep 2003 16:41:21 +1000
From: Sisyphus <kalinabears@iinet.net.au>
Subject: Re: tar gone wild under perl
Message-Id: <3f5ec83f$0$23596$5a62ac22@freenews.iinet.net.au>

Marshall Dudley wrote:

> 
> The perl code line I am using is:
> 
> exec("/usr/bin/tar cflz - $store_path
> /home/kingcart/html/store/$username");
> 

Any warnings ?

Does 'system()', instead of 'exec()', produce more desirable behaviour ?
If so, see 'perldoc -f exec' (and also 'perldoc -f system') for a 
possible explanation.

Hth.

Cheers,
Rob


-- 
PLEASE NOTE: comp.infosystems.www.authoring.cgi is a
SELF-MODERATED newsgroup. aa.net and boutell.com are
NOT the originators of the articles and are NOT responsible
for their content.

HOW TO POST to comp.infosystems.www.authoring.cgi:
http://www.thinkspot.net/ciwac/howtopost.html


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

Date: Wed, 17 Sep 2003 21:15:18 -0700
From: "Tom" <tom@nosleep.net>
Subject: wtf is the deal?
Message-Id: <3f6930ae$1@nntp0.pdx.net>

I have made several posts asking the same type dmb questions. Other people
ask similar questions and get answers almost immediately.
My questions go unanswered permanently.
I posted code, explained the issue in detail and have done everything
everyone else has done, to no avail.
WTF gives?
I've asked as many different ways as I can think.




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

Date: Thu, 18 Sep 2003 04:26:05 GMT
From: Uri Guttman <uri@stemsystems.com>
Subject: Re: wtf is the deal?
Message-Id: <x7isnqvi1v.fsf@mail.sysarch.com>

>>>>> "T" == Tom  <tom@nosleep.net> writes:

  T> I have made several posts asking the same type dmb questions. Other people
  T> ask similar questions and get answers almost immediately.
  T> My questions go unanswered permanently.
  T> I posted code, explained the issue in detail and have done everything
  T> everyone else has done, to no avail.
  T> WTF gives?
  T> I've asked as many different ways as I can think.

i see two posts and both were answered by bob walton who told you to
look at the MLDBM module which is a good answer. what more do you want?
have you looked at the module? installed it? rtfm'ed it?

how many ways do you need to be told to use that module?

uri

-- 
Uri Guttman  ------  uri@stemsystems.com  -------- http://www.stemsystems.com
--Perl Consulting, Stem Development, Systems Architecture, Design and Coding-
Search or Offer Perl Jobs  ----------------------------  http://jobs.perl.org
Damian Conway Class in Boston - Sept 2003 -- http://www.stemsystems.com/class


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

Date: Wed, 17 Sep 2003 21:39:08 -0700
From: "Tom" <tom@nosleep.net>
Subject: Re: wtf is the deal?
Message-Id: <3f693644$1@nntp0.pdx.net>

I'm sorry, there must be something wrong with my isp news again, as I don't
see any responses at all.
I'm not sure why yours showed up, but the others didn't. I did not cross
post, so they must have showed up out of my thread.

Thanks,
Tom

"Uri Guttman" <uri@stemsystems.com> wrote in message
news:x7isnqvi1v.fsf@mail.sysarch.com...
> >>>>> "T" == Tom  <tom@nosleep.net> writes:
>
>   T> I have made several posts asking the same type dmb questions. Other
people
>   T> ask similar questions and get answers almost immediately.
>   T> My questions go unanswered permanently.
>   T> I posted code, explained the issue in detail and have done everything
>   T> everyone else has done, to no avail.
>   T> WTF gives?
>   T> I've asked as many different ways as I can think.
>
> i see two posts and both were answered by bob walton who told you to
> look at the MLDBM module which is a good answer. what more do you want?
> have you looked at the module? installed it? rtfm'ed it?
>
> how many ways do you need to be told to use that module?
>
> uri
>
> -- 
> Uri Guttman  ------  uri@stemsystems.com  -------- 
http://www.stemsystems.com
> --Perl Consulting, Stem Development, Systems Architecture, Design and
Coding-
> Search or Offer Perl Jobs  ---------------------------- 
http://jobs.perl.org
> Damian Conway Class in Boston - Sept 2003 -- 
http://www.stemsystems.com/class




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

Date: Wed, 17 Sep 2003 21:40:04 -0700
From: "Tom" <tom@nosleep.net>
Subject: Re: wtf is the deal?
Message-Id: <3f69367c$1@nntp0.pdx.net>

actually, I can't see his posts anywhere.




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

Date: Thu, 18 Sep 2003 04:57:19 GMT
From: Uri Guttman <uri@stemsystems.com>
Subject: Re: wtf is the deal?
Message-Id: <x7ekyevgls.fsf@mail.sysarch.com>

>>>>> "T" == Tom  <tom@nosleep.net> writes:

  T> actually, I can't see his posts anywhere.


http://www.google.com/groups?hl=en&lr=&ie=UTF-8&oe=UTF-8&threadm=3F67A791.5090609%40rochester.rr.com&rnum=1&prev=/groups%3Fhl%3Den%26lr%3D%26ie%3DUTF-8%26oe%3DUTF-8%26as_drrb%3Db%26q%3Dgroup%253Acomp.lang.perl.misc%2Bauthor%253Abob%2Bauthor%253Awalton%26btnG%3DGoogle%2BSearch%26as_mind%3D16%26as_minm%3D9%26as_miny%3D2003%26as_maxd%3D17%26as_maxm%3D9%26as_maxy%3D2003

google sure can.

uri

-- 
Uri Guttman  ------  uri@stemsystems.com  -------- http://www.stemsystems.com
--Perl Consulting, Stem Development, Systems Architecture, Design and Coding-
Search or Offer Perl Jobs  ----------------------------  http://jobs.perl.org
Damian Conway Class in Boston - Sept 2003 -- http://www.stemsystems.com/class


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

Date: Wed, 17 Sep 2003 22:56:09 -0700
From: "Tom" <tom@nosleep.net>
Subject: Re: wtf is the deal?
Message-Id: <3f694851@nntp0.pdx.net>

thanks
"Uri Guttman" <uri@stemsystems.com> wrote in message
news:x7ekyevgls.fsf@mail.sysarch.com...
> >>>>> "T" == Tom  <tom@nosleep.net> writes:
>
>   T> actually, I can't see his posts anywhere.
>
>
>
http://www.google.com/groups?hl=en&lr=&ie=UTF-8&oe=UTF-8&threadm=3F67A791.5090609%40rochester.rr.com&rnum=1&prev=/groups%3Fhl%3Den%26lr%3D%26ie%3DUTF-8%26oe%3DUTF-8%26as_drrb%3Db%26q%3Dgroup%253Acomp.lang.perl.misc%2Bauthor%253Abob%2Bauthor%253Awalton%26btnG%3DGoogle%2BSearch%26as_mind%3D16%26as_minm%3D9%26as_miny%3D2003%26as_maxd%3D17%26as_maxm%3D9%26as_maxy%3D2003
>
> google sure can.
>
> uri
>
> -- 
> Uri Guttman  ------  uri@stemsystems.com  -------- 
http://www.stemsystems.com
> --Perl Consulting, Stem Development, Systems Architecture, Design and
Coding-
> Search or Offer Perl Jobs  ---------------------------- 
http://jobs.perl.org
> Damian Conway Class in Boston - Sept 2003 -- 
http://www.stemsystems.com/class




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

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

Ron wrote:

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

(---^


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

 ...
-- 
Bob Walton



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

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


Administrivia:

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

	subscribe perl-users
or:
	unsubscribe perl-users

to almanac@ruby.oce.orst.edu.  

To submit articles to comp.lang.perl.announce, send your article to
clpa@perl.com.

To request back copies (available for a week or so), send your request
to almanac@ruby.oce.orst.edu with the command "send perl-users x.y",
where x is the volume number and y is the issue number.

For other requests pertaining to the digest, send mail to
perl-users-request@ruby.oce.orst.edu. Do not waste your time or mine
sending perl questions to the -request address, I don't have time to
answer them even if I did know the answer.


------------------------------
End of Perl-Users Digest V10 Issue 5521
***************************************


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