Help - Search - Member List - Calendar
Full Version: combinations
WorkTheWeb Forums > Webmaster Resources > Perl Beginner Help
Pages: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44
Support our Sponsors!
John W. Krahn
Jay Savage wrote:
QUOTE
On 4/27/05, John W. Krahn <[Email Removed]> wrote:

Jay Savage wrote:

4> open (V4, "samcmd v4 2>&1 |" ) || die "unable to open pipe...
Broken?$!";

Don't do this.  the precedence of || is too high.  your code attempts
to open a pipe, and if it can't, then it attempts to open "die..." and
starts throwing exceptions.

No, that is NOT what happens, it will NEVER attempt to open "die..." with or
without the parentheses.  The ONLY time it will attempt to open "die..." is if
there are no parentheses and the expression on the left hand side of the ||
operator evaluates to false.

open V4, '0' || die $!;

But even then it will NOT attempt to open "die..." because die() exits the
program!

Is stand corrected.  There is no exception; I guess any time I've run
into it, I've relied on whatever was opened, and died anyway.  But I
don't know what else to call opens behavior, except attempting to open
die.  Except in the case of parenthesis, as you noted, the behavior of
open || die sure looks like this to me:  open (X, badfile || die).
The only difference between the two expressions below is the
precedence of the operator.

jsavage@ariadne:~> perl -e 'open FH, "< BAdFiLe" || die "$!"'
jsavage@ariadne:~> perl -e 'open FH, "< BAdFiLe" or die "$!"'
No such file or directory at -e line 1.

Open may not technically be trying to open an expression and failing,
I don't know.  To be honest, I've never taken apart the source to see.
But the appearance is certainly that that's what happens, and the
result is so similar as to not matter.  Especially consider the
following:

perl -e 'open FH, "< BAdFiLe" || die or die "$!"; print "didnt dien" '
No such file or directory at -e line 1.

Where did the first die go if || didn't attempt to pass it to open?

if the reason for the failed open were the attempt to open "BAdFiLe",
the first die would execute and the program would exit bore it got to
the second.  But clearly that's not what's happening.  The first die
is getting slurped up by ||, which is presumably trying to pass it on
to open.  When that fails, the second die executes, exiting with $!.
at least that's what it looks like to me.

So what's really happeneing here?

perldoc perlop

[snip]

C-style Logical Or

Binary "||" performs a short-circuit logical OR operation. That is, if
^^^^^^^^^^^^^
the left operand is true, the right operand is not even evaluated.
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Perhaps this will help illustrate:

$ perl -MO=Deparse,-p -e'open IN, "BADFILE" || die "ERROR: $!"'
open(IN, 'BADFILE');
-e syntax OK
$ perl -MO=Deparse,-p -e'open IN, "BADFILE" || die or die "ERROR: $!"'
(open(IN, 'BADFILE') or die("ERROR: $!"));
-e syntax OK

Because the string "BADFILE" is true, which is determined at compile time, it
is as if "|| die" did not exist at all!

Of course if the file name is in a variable then it must be evaluated at run time:

$ perl -MO=Deparse,-p -e'open IN, $ARGV[0] || die "ERROR: $!"' BADFILE
open(IN, ($ARGV[0] || die("ERROR: $!")));
-e syntax OK
$ perl -MO=Deparse,-p -e'open IN, $ARGV[0] || die or die "ERROR: $!"' BADFILE
(open(IN, ($ARGV[0] || die)) or die("ERROR: $!"));
-e syntax OK

Where "|| die" will only be evaluated if the variable is false (undef, 0, '0'
or '').



John
--
use Perl;
program
fulfillment

John W. Krahn
Ing. Branislav Gerzo wrote:
QUOTE
JupiterHost.Net [JN], on Thursday, April 28, 2005 at 09:11 (-0500)
contributed this to our collective wisdom:

(really beginners) could think "@a" will empty array, which is not
true.

JN> yes it is true, they are both empty lists:

@a will not empty array, here it is:

my @a = q{foo bar};
@a;
print @a;

against

my @a = q{foo bar};
@a = ( );
print @a;

I hope you see the difference :)

And you would as well if you had warnings enabled as the first example would
warn you about using an array in void context.

$ perl -le'
use warnings;
my @a = qw{foo bar};
@a;
print @a;
'
Useless use of private array in void context at -e line 3.
foobar



John
--
use Perl;
program
fulfillment

So which is safer more ideal to use : || , or


Derek B. Smith
OhioHealth IT
UNIX / TSM / EDM Teams





"John W. Krahn"
<[Email Removed]
QUOTE
To
Perl Beginners <[Email Removed]

04/28/2005 07:55 cc
PM
Subject
Re: REGEXP removing - il- - -b-f
and - il- - - - f










Jay Savage wrote:
QUOTE
On 4/27/05, John W. Krahn <[Email Removed]> wrote:

Jay Savage wrote:

4> open (V4, "samcmd v4 2>&1 |" ) || die "unable to open pipe...
Broken?$!";

Don't do this.  the precedence of || is too high.  your code attempts
to open a pipe, and if it can't, then it attempts to open "die..." and
starts throwing exceptions.

No, that is NOT what happens, it will NEVER attempt to open "die..." with
or
without the parentheses.  The ONLY time it will attempt to open "die..."
is if
there are no parentheses and the expression on the left hand side of the
||
operator evaluates to false.

open V4, '0' || die $!;

But even then it will NOT attempt to open "die..." because die() exits
the
program!

Is stand corrected.  There is no exception; I guess any time I've run
into it, I've relied on whatever was opened, and died anyway.  But I
don't know what else to call opens behavior, except attempting to open
die.  Except in the case of parenthesis, as you noted, the behavior of
open || die sure looks like this to me:  open (X, badfile || die).
The only difference between the two expressions below is the
precedence of the operator.

jsavage@ariadne:~> perl -e 'open FH, "< BAdFiLe" || die "$!"'
jsavage@ariadne:~> perl -e 'open FH, "< BAdFiLe" or die "$!"'
No such file or directory at -e line 1.

Open may not technically be trying to open an expression and failing,
I don't know.  To be honest, I've never taken apart the source to see.
But the appearance is certainly that that's what happens, and the
result is so similar as to not matter.  Especially consider the
following:

perl -e 'open FH, "< BAdFiLe" || die or die "$!"; print "didnt dien"
'
No such file or directory at -e line 1.

Where did the first die go if || didn't attempt to pass it to open?

if the reason for the failed open were the attempt to open "BAdFiLe",
the first die would execute and the program would exit bore it got to
the second.  But clearly that's not what's happening.  The first die
is getting slurped up by ||, which is presumably trying to pass it on
to open.  When that fails, the second die executes, exiting with $!.
at least that's what it looks like to me.

So what's really happeneing here?

perldoc perlop

[snip]

C-style Logical Or

Binary "||" performs a short-circuit logical OR operation. That is,
if
^^^^^^^^^^^^^
the left operand is true, the right operand is not even evaluated.
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Perhaps this will help illustrate:

$ perl -MO=Deparse,-p -e'open IN, "BADFILE" || die "ERROR: $!"'
open(IN, 'BADFILE');
-e syntax OK
$ perl -MO=Deparse,-p -e'open IN, "BADFILE" || die or die "ERROR: $!"'
(open(IN, 'BADFILE') or die("ERROR: $!"));
-e syntax OK

Because the string "BADFILE" is true, which is determined at compile time,
it
is as if "|| die" did not exist at all!

Of course if the file name is in a variable then it must be evaluated at
run time:

$ perl -MO=Deparse,-p -e'open IN, $ARGV[0] || die "ERROR: $!"' BADFILE
open(IN, ($ARGV[0] || die("ERROR: $!")));
-e syntax OK
$ perl -MO=Deparse,-p -e'open IN, $ARGV[0] || die or die "ERROR: $!"'
BADFILE
(open(IN, ($ARGV[0] || die)) or die("ERROR: $!"));
-e syntax OK

Where "|| die" will only be evaluated if the variable is false (undef, 0,
'0'
or '').



John
--
use Perl;
program
fulfillment

--
To unsubscribe, e-mail: [Email Removed]
For additional commands, e-mail: [Email Removed]
<http://learn.perl.org/> <http://learn.perl.org/first-response>

Ing. Branislav Gerzo
[Email Removed] [D], on Friday, April 29, 2005 at 08:43 (-0400)
thoughtfully wrote the following:

D>So which is safer more ideal to use : || , or

I think "or" is better - it makes perl language more readable for
beginners.

--

How do you protect mail on web? I use http://www.2pu.net

[Join the Navy and see the world... Through a porthole.]

well, I am trying to get beyond a beginner as I have doing Perl for 3
years now so is your answer still the same?

thanks,

derek




"Ing. Branislav
Gerzo"
<[Email Removed]> To
[Email Removed]
04/29/2005 09:09 cc
AM
Subject
Re: REGEXP removing - il- - -b-f
and - il- - - - f










[Email Removed] [D], on Friday, April 29, 2005 at 08:43 (-0400)
thoughtfully wrote the following:

D>So which is safer more ideal to use : || , or

I think "or" is better - it makes perl language more readable for
beginners.

--

How do you protect mail on web? I use http://www.2pu.net

[Join the Navy and see the world... Through a porthole.]



--
To unsubscribe, e-mail: [Email Removed]
For additional commands, e-mail: [Email Removed]
<http://learn.perl.org/> <http://learn.perl.org/first-response>

Ing. Branislav Gerzo
[Email Removed] [D], on Friday, April 29, 2005 at 09:30 (-0400)
wrote about:

DOc> well, I am trying to get beyond a beginner as I have doing Perl for 3
DOc> years now so is your answer still the same?

I think really good programmers write "nice" readable programs
(scripts), so begginers should understand that sooner. I think, that's
why better using "or" instead "||".

--

How do you protect mail on web? I use http://www.2pu.net

["Pooh was a wise Taoist, wasn't he?" -- Robin Mowat]

John Doe
Am Freitag, 29. April 2005 14.43 schrieb [Email Removed]:
QUOTE
So which is safer more ideal to use :  || , or


Derek B. Smith
OhioHealth IT
UNIX / TSM / EDM Teams
[...]


The only difference between "||" and "or" is the precedence, and the
precedence of "=" lies between them.

To my understanding, in the "assign or die" special case,

my $a=do_something_which_can_fail() or handle_exception();

is more logic than

my $a=do_something_which_can_fail() || handle_exception();

because something should be assigned to $a, and if that fails, the app should
e.g. die. This way, the exception handling is not part of the assignement.

On the other side, I would use

my $a=do_something_which_can_fail() || provide_some_default();

because the exception handling consists of providing a value.

Just my personal way to look at it :-)

joe

Peter Rabbitson
QUOTE
I think really good programmers write "nice" readable programs
(scripts), so begginers should understand that sooner. I think, that's
why better using "or" instead "||".

Come-on guys! Read your mails. John Krahn spent the time to write a
wonderful explanation why || simply DOES NOT WORK when used with open
(although it works for the general case, which does not constitute the term
'works'). Don't lure beginners into thinking this is a matter of style (like
I used to think myself). There is a very rigid logical explanation behibd
it, and whether you are a beginner or not doesn't change the facts.

Peter

Errin M HMMA/IT Larsen
QUOTE
-----Original Message-----
From: John Doe [mailto:[Email Removed]]
Sent: Friday, April 29, 2005 8:50 AM
To: [Email Removed]
Subject: Re: REGEXP removing - il- - -b-f and - il- - - - f


Am Freitag, 29. April 2005 14.43 schrieb [Email Removed]:
So which is safer more ideal to use :  || , or


Derek B. Smith
OhioHealth IT
UNIX / TSM / EDM Teams
[...]

The only difference between "||" and "or" is the precedence, and the
precedence of "=" lies between them.

To my understanding, in the "assign or die" special case,

my $a=do_something_which_can_fail() or handle_exception();



I'm sure I'll be corrected if I am wrong, but I believe that Perl sees
the above line of code like this:

( my $a = do_something_which_can_fail() ) or ( handle_exception() );

Because of the low precedence of the "or" operator. Therefore, Perl
will try to assign the return value of "do_something_which_can_fail()"
subroutine to $a, and if it can't, THEN perl will execute the
"handle_exception()" subroutine. This is probably what the coder
wanted.



QUOTE

is more logic than

my $a=do_something_which_can_fail() || handle_exception();


Perl sees THIS line of code like this:

my $a = ( ( do_something_which_can_fail() ) || ( handle_exception() )
);

Because of the high precedence of the "||" operator. Therefore, perl
will run the "do_something which can fail()" subroutine, and if it
succeeds, assign the value returned to $a. OTHERWISE, if it fails, the
return value from "handle_exception()" subroutine will be assigned to
$a. This is probably NOT what you want to happen.


QUOTE

because something should be assigned to $a, and if that
fails, the app should
e.g. die. This way, the exception handling is not part of the
assignement.

On the other side, I would use

my $a=do_something_which_can_fail() || provide_some_default();

because the exception handling consists of providing a value.

Just my personal way to look at it :-)

joe


--Errin Larsen

Manav Mathur
|-----Original Message-----
|From: Ing. Branislav Gerzo [mailto:[Email Removed]]
|Sent: Friday, April 29, 2005 7:11 PM
|To: [Email Removed]
|Subject: Re: REGEXP removing - il- - -b-f and - il- - - - f
|
|
|[Email Removed] [D], on Friday, April 29, 2005 at 09:30 (-0400)
|wrote about:
|
|DOc> well, I am trying to get beyond a beginner as I have doing Perl for 3
|DOc> years now so is your answer still the same?
|
|I think really good programmers write "nice" readable programs
|(scripts), so begginers should understand that sooner. I think, that's
|why better using "or" instead "||".
|

'||' and 'or' have different precedences. Some important operators which
have a higher precedence than 'or' but lower precedence than '||' are the
comma operator, the assignment operator, '=>'(dunno what this operator is
called in Perlism).

Code involving these operators will break if you simply assume that the
difference between '||' and 'or' is only style.
eg
$var = $a || $b
$var = $a or $b ##there you go

open A,"$file" or die("$! : whoopsie!!")
open A,"$file" || die("$! : whoopsie!!")

or in a more wierd manner, where unbeknownst to you, the entire context of
evaluation changes.

##code starts
use strict ;
use warnings ;
sub sub_returns_array {
return wantarray() ? qw/abc def crf/ : "scalar returned :-/" ;
}
my @arr1 = sub_returns_array || die ;
my @arr2 = sub_returns_array or die ;
print "arr1 : @arr1n" ;
print "arr2 : @arr2" ;
##code ends

Manav


|--
|
|How do you protect mail on web? I use http://www.2pu.net
|
|["Pooh was a wise Taoist, wasn't he?" -- Robin Mowat]
|
|
|
|--
|To unsubscribe, e-mail: [Email Removed]
|For additional commands, e-mail: [Email Removed]
|<http://learn.perl.org/> <http://learn.perl.org/first-response>
|
|


*********************************************************
Disclaimer:

The contents of this E-mail (including the contents of the enclosure(s) or attachment(s) if any) are privileged and confidential material of MBT and should not be disclosed to, used by or copied in any manner by anyone other than the intended addressee(s). In case you are not the desired addressee, you should delete this message and/or re-direct it to the sender. The views expressed in this E-mail message (including the enclosure(s) or attachment(s) if any) are those of the individual sender, except where the sender expressly, and with authority, states them to be the views of MBT.

This e-mail message including attachment/(s), if any, is believed to be free of any virus. However, it is the responsibility of the recipient to ensure that it is virus free and MBT is not responsible for any loss or damage arising in any way from its use

*********************************************************

Jay Savage
On 4/28/05, John W. Krahn <[Email Removed]> wrote:
QUOTE
Jay Savage wrote:
On 4/27/05, John W. Krahn <[Email Removed]> wrote:

Jay Savage wrote:

4> open (V4, "samcmd v4 2>&1 |" ) || die "unable to open pipe...
Broken?$!";

Don't do this.  the precedence of || is too high.  your code attempts
to open a pipe, and if it can't, then it attempts to open "die..." and
starts throwing exceptions.

No, that is NOT what happens, it will NEVER attempt to open "die..." with or
without the parentheses.  The ONLY time it will attempt to open "die..." is if
there are no parentheses and the expression on the left hand side of the ||
operator evaluates to false.

open V4, '0' || die $!;

But even then it will NOT attempt to open "die..." because die() exits the
program!

Is stand corrected.  There is no exception; I guess any time I've run
into it, I've relied on whatever was opened, and died anyway.  But I
don't know what else to call opens behavior, except attempting to open
die.  Except in the case of parenthesis, as you noted, the behavior of
open || die sure looks like this to me:  open (X, badfile || die).
The only difference between the two expressions below is the
precedence of the operator.

jsavage@ariadne:~> perl -e 'open FH, "< BAdFiLe" || die "$!"'
jsavage@ariadne:~> perl -e 'open FH, "< BAdFiLe" or die "$!"'
No such file or directory at -e line 1.

Open may not technically be trying to open an expression and failing,
I don't know.  To be honest, I've never taken apart the source to see.
But the appearance is certainly that that's what happens, and the
result is so similar as to not matter.  Especially consider the
following:

perl -e 'open FH, "< BAdFiLe" || die or die "$!"; print "didnt dien" '
No such file or directory at -e line 1.

Where did the first die go if || didn't attempt to pass it to open?

if the reason for the failed open were the attempt to open "BAdFiLe",
the first die would execute and the program would exit bore it got to
the second.  But clearly that's not what's happening.  The first die
is getting slurped up by ||, which is presumably trying to pass it on
to open.  When that fails, the second die executes, exiting with $!.
at least that's what it looks like to me.

So what's really happeneing here?

perldoc perlop

[snip]

C-style Logical Or

Binary "||" performs a short-circuit logical OR operation.  That is, if
^^^^^^^^^^^^^
the left operand is true, the right operand is not even evaluated.
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Perhaps this will help illustrate:

$ perl -MO=Deparse,-p -e'open IN, "BADFILE" || die "ERROR: $!"'
open(IN, 'BADFILE');
-e syntax OK
$ perl -MO=Deparse,-p -e'open IN, "BADFILE" || die or die "ERROR: $!"'
(open(IN, 'BADFILE') or die("ERROR: $!"));
-e syntax OK

Because the string "BADFILE" is true, which is determined at compile time, it
is as if "|| die" did not exist at all!

Of course if the file name is in a variable then it must be evaluated at run time:

$ perl -MO=Deparse,-p -e'open IN, $ARGV[0] || die "ERROR: $!"' BADFILE
open(IN, ($ARGV[0] || die("ERROR: $!")));
-e syntax OK
$ perl -MO=Deparse,-p -e'open IN, $ARGV[0] || die or die "ERROR: $!"' BADFILE
(open(IN, ($ARGV[0] || die)) or die("ERROR: $!"));
-e syntax OK

Where "|| die" will only be evaluated if the variable is false (undef, 0, '0'
or '').



Logical "or" is also a short circuit operator, also from perlop:

As more readable alternatives to "&&" and "||" when used for control
flow, Perl provides "and" and "or" operators (see below). The
short-circuit behavior is identical. The precedence of "and" and "or" is
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
much lower, however, so that you can safely use them after a list
operator without the need for parentheses:

In other words, the only differnce between "||" and "or" is
precedence. And precedence is what creates this:

jsavage@ariadne:~> perl -MO=Deparse,-p -e'$i=<STDIN>;open IN, $i ||
die or die "ERROR: $!"'
($i = <STDIN>);
(open(IN, ($i || die)) or die("ERROR: $!"));
-e syntax OK

I will admit that my response to OP didn't take into account that, in
his particular case, the argument to open was a literal and "||" was
being evaluated at compile time. But the fact remains that it is
simply and demonstrably not true that open will never attempt to open
die, or that the attempt to open die will call die and exit the
program. And I would have to say that the case where || is evaluated
at runtime is by far the more common case.

Thank you, though for the lesson on the differences between compile
time and runtime execution (and the reminder about how useful Deparse
can be).

John W. Krahn
Peter Rabbitson wrote:
QUOTE
I think really good programmers write "nice" readable programs
(scripts), so begginers should understand that sooner. I think, that's
why better using "or" instead "||".


Come-on guys! Read your mails. John Krahn spent the time to write a
wonderful explanation why || simply DOES NOT WORK when used with open
(although it works for the general case, which does not constitute the term
'works'). Don't lure beginners into thinking this is a matter of style (like
I used to think myself). There is a very rigid logical explanation behibd
it, and whether you are a beginner or not doesn't change the facts.

I did not say that it does not work, for example this is completely acceptable:

open( IN, $file ) || die "error: $!";



John
--
use Perl;
program
fulfillment

John W. Krahn
Jay Savage wrote:
QUOTE

[big snip]

I will admit that my response to OP didn't take into account that, in
his particular case, the argument to open was a literal and "||" was
being evaluated at compile time.  But the fact remains that it is
simply and demonstrably not true that open will never attempt to open
die, or that the attempt to open die will call die and exit the
program.

You say that it is "demonstrably not true", so please demonstrate. :-)


John
--
use Perl;
program
fulfillment

John W. Krahn
[Email Removed] wrote:
QUOTE
I was thinking of using a hash of arrays b/c I want to look-up each array
by a certain string and that string would the % string.
My goal is to populate a hash of some sort with the % string and its
associated F string.
Here is the data file:

1    2005/01/20 15:39  17  2%  -il-o-b-----  sg F01000
2    2005/01/20 15:53  14  1%  -il-o-b-----  sg F01001
3    2005/01/18 09:53    2  0%  -il-o-b-----  sg F01002
4    2005/02/04 16:41  196 100%  -il-o-b----f  sg F01003
5    2005/02/05 21:13  305 100%  -il-o-b----f  sg F01004

#!/usr/bin/perl
use strict;
use warnings;
$ENV{"PATH"} = qq(/opt/SUNWsamfs/sbin:/usr/bin:/usr/sbin:/usr/local/log);
open (V4, "samcmd v4 2>&1 |" ) or die "unable to open pipe... Broken? $!";
my %HoA = ();
my $i =0;
foreach (<V4>) {
s <sg> ();
^

The whitespace there will not work for all versions of Perl. Are you sure
that it works for you?


QUOTE
s {-*} ()g;

The hyphen is not special in a regular expression, it does not need to be
escaped. You are telling the substitution operator to replace all zero
occurrences of '-' which is unnecessary.

$ perl -Mre=debug -e'$_ = q[ 1 2005/01/20 15:39 17 2% -il-o-b-----
sg F01000]; s{-*} ()g;' 2>&1 | grep -c 'Match successful'
55
$ perl -Mre=debug -e'$_ = q[ 1 2005/01/20 15:39 17 2% -il-o-b-----
sg F01000]; s{-+} ()g;' 2>&1 | grep -c 'Match successful'
4

As you can see the regex '-*' matches 55 times while the regex '-+' only
matches 4 times.

Besides, it would be more efficient to use the transliteration operator.

tr/-//d;


QUOTE
s {w+} ();
$HoA{$i++} = (split)[-1] if (m/f01(d+) && (d+%) /gi  );

You are storing the value of $i as the key which starts at 0 and is
incremented for each line of input so why not just use an array and push the
values onto it? You have included the string ' && ' in your regular
expression but I don't see that string anywhere in your data? You are using
capturing parentheses in the regular expression but you are not using those
captured strings anywhere?


QUOTE
}
close (V4) or die "unable to close pipe $!";
print "n";

for my $d (keys %HoA) {
print "$d: @{ $HoA{$d} }n";

You are trying to use a scalar value ($HoA{$d}) as an array which strict
should complain about.

QUOTE
}


John
--
use Perl;
program
fulfillment

John,

the reg exp s <-+> ();
^
was changed to

y/sg//;;
y/-//d;
s{w+} ();
to exclude the spaces and use y... thx
why are thre operators y or tr more efficient since these operators do not
use pattern matching?

Originally I was using an array, actually 2 arrays one with all f string s
and one with all % strings.
To me it makes more sense to use a hash b/c each F string needs to be
pulled with its associative n% string.
This is why I want to populate a hash of arrays.

Below is what is should of read for my population of the hash.

$HoA{$i++} = (split)[-1] if (m/f01(d+)(d+%) /gi );




ciao,

derek : )




"John W. Krahn"
<[Email Removed]
QUOTE
To
Perl Beginners <[Email Removed]

05/01/2005 08:30 cc
PM
Subject
Re: populating a hash with % used
as the key and F string as
thevalue










[Email Removed] wrote:
QUOTE
I was thinking of using a hash of arrays b/c I want to look-up each array
by a certain string and that string would the % string.
My goal is to populate a hash of some sort with the % string and its
associated F string.
Here is the data file:

1    2005/01/20 15:39  17  2%  -il-o-b-----  sg F01000
2    2005/01/20 15:53  14  1%  -il-o-b-----  sg F01001
3    2005/01/18 09:53    2  0%  -il-o-b-----  sg F01002
4    2005/02/04 16:41  196 100%  -il-o-b----f  sg F01003
5    2005/02/05 21:13  305 100%  -il-o-b----f  sg F01004

#!/usr/bin/perl
use strict;
use warnings;
$ENV{"PATH"} = qq(/opt/SUNWsamfs/sbin:/usr/bin:/usr/sbin:/usr/local/log);
open (V4, "samcmd v4 2>&1 |" ) or die "unable to open pipe... Broken?
$!";
my %HoA = ();
my $i =0;
foreach (<V4>) {
s <sg> ();
^

The whitespace there will not work for all versions of Perl. Are you sure
that it works for you?


QUOTE
s {-*} ()g;

The hyphen is not special in a regular expression, it does not need to be
escaped. You are telling the substitution operator to replace all zero
occurrences of '-' which is unnecessary.

$ perl -Mre=debug -e'$_ = q[ 1 2005/01/20 15:39 17 2% -il-o-b-----

sg F01000]; s{-*} ()g;' 2>&1 | grep -c 'Match successful'
55
$ perl -Mre=debug -e'$_ = q[ 1 2005/01/20 15:39 17 2% -il-o-b-----

sg F01000]; s{-+} ()g;' 2>&1 | grep -c 'Match successful'
4

As you can see the regex '-*' matches 55 times while the regex '-+' only
matches 4 times.

Besides, it would be more efficient to use the transliteration operator.

tr/-//d;


QUOTE
s {w+} ();
$HoA{$i++} = (split)[-1] if (m/f01(d+) && (d+%) /gi  );

You are storing the value of $i as the key which starts at 0 and is
incremented for each line of input so why not just use an array and push
the
values onto it? You have included the string ' && ' in your regular
expression but I don't see that string anywhere in your data? You are
using
capturing parentheses in the regular expression but you are not using those
captured strings anywhere?


QUOTE
}
close (V4) or die "unable to close pipe $!";
print "n";

for my $d (keys %HoA) {
print "$d: @{ $HoA{$d} }n";

You are trying to use a scalar value ($HoA{$d}) as an array which strict
should complain about.

QUOTE
}


John
--
use Perl;
program
fulfillment

--
To unsubscribe, e-mail: [Email Removed]
For additional commands, e-mail: [Email Removed]
<http://learn.perl.org/> <http://learn.perl.org/first-response>

Marcos Rebelo
I'm getting crazy

I have the Xerces (I think) installed on Cygwin.

Now I have to set some variables but I dont know to what, can someone help me

XERCES_LIB
XERCES_INCLUDE
XERCESCROOT
XERCES_CONFIG

Thanks

John Doe
Am Montag, 2. Mai 2005 03.49 schrieb [Email Removed]:
QUOTE
John,

the reg exp s <-+> ();
^
was changed to

y/sg//;;
y/-//d;
s{w+} ();
to exclude the spaces and use y... thx
why are thre operators y or tr more efficient since these operators do not
use pattern matching?

Don't know the internal details, but tr needs no backtracking, capturing and
such, it can simply take a char after the other and replace it with another
one. So the implementation of the algorithm must be much much easier.

QUOTE
Originally I was using an array, actually 2 arrays one with all f string s
and one with all % strings.
To me it makes more sense to use a hash b/c each F string needs to be
pulled with its associative n% string.
This is why I want to populate a hash of arrays.

Would another strategy be easier and more efficient to fulfill this
requirement?

* If the format of all your data lines is "consistent", you could use split on
s+ to get the data fields instead of a tr/m cascade.

* Then, if I understand you correctly, you wantto build a hash with % keys and
F... values. This could be done with code like

push @{$lookup_hash{$pct_value}}, $F_value;

eventually, you even want a 2nd level hash with the F field number as key, if
the F values are unique over the whole file and the last field alway begins
with an F.

Or am I overlooking something?

hth, joe


QUOTE
Below is what is should of read for my population of the hash.

$HoA{$i++} = (split)[-1] if (m/f01(d+)(d+%) /gi  );

ciao,
derek : )

[...]
QUOTE
[Email Removed] wrote:
I was thinking of using a hash of arrays b/c I want to look-up each array
by a certain string and that string would the % string.
My goal is to populate a hash of some sort with the % string and its
associated F string.
Here is the data file:

1    2005/01/20 15:39  17  2%  -il-o-b-----  sg F01000
2    2005/01/20 15:53  14  1%  -il-o-b-----  sg F01001
3    2005/01/18 09:53    2  0%  -il-o-b-----  sg F01002
4    2005/02/04 16:41  196 100%  -il-o-b----f  sg F01003
5    2005/02/05 21:13  305 100%  -il-o-b----f  sg F01004

#!/usr/bin/perl
use strict;
use warnings;
$ENV{"PATH"} = qq(/opt/SUNWsamfs/sbin:/usr/bin:/usr/sbin:/usr/local/log);
open (V4, "samcmd v4 2>&1 |" ) or die "unable to open pipe... Broken?

$!";

my %HoA = ();
my $i =0;
foreach (<V4>) {

s <sg> ();

^
The whitespace there will not work for all versions of Perl.  Are you sure
that it works for you?

s {-*} ()g;

The hyphen is not special in a regular expression, it does not need to be
escaped.  You are telling the substitution operator to replace all zero
occurrences of '-' which is unnecessary.

$ perl -Mre=debug -e'$_ = q[ 1    2005/01/20 15:39  17  2%  -il-o-b-----

sg F01000]; s{-*} ()g;' 2>&1 | grep -c 'Match successful'
55
$ perl -Mre=debug -e'$_ = q[ 1    2005/01/20 15:39  17  2%  -il-o-b-----

sg F01000]; s{-+} ()g;' 2>&1 | grep -c 'Match successful'
4

As you can see the regex '-*' matches 55 times while the regex '-+' only
matches 4 times.

Besides, it would be more efficient to use the transliteration operator.

tr/-//d;

s {w+} ();

$HoA{$i++} = (split)[-1] if (m/f01(d+) && (d+%) /gi  );

You are storing the value of $i as the key which starts at 0 and is
incremented for each line of input so why not just use an array and push
the
values onto it?  You have included the string ' && ' in your regular
expression but I don't see that string anywhere in your data?  You are
using
capturing parentheses in the regular expression but you are not using those
captured strings anywhere?

}
close (V4) or die "unable to close pipe $!";
print "n";

for my $d (keys %HoA) {
print "$d: @{ $HoA{$d} }n";

You are trying to use a scalar value ($HoA{$d}) as an array which strict
should complain about.

}

John
[...]


John Doe
Am Montag, 2. Mai 2005 09.44 schrieb John Doe:
QUOTE
Am Montag, 2. Mai 2005 03.49 schrieb [Email Removed]:
John,

the reg exp s <-+> ();
^
was changed to

y/sg//;;
y/-//d;
s{w+} ();
to exclude the spaces and use y... thx
why are thre operators y or tr more efficient since these operators do
not use pattern matching?

Don't know the internal details, but tr needs no backtracking, capturing
and such, it can simply take a char after the other and replace it with
another one. So the implementation of the algorithm must be much much
easier.

Originally I was using an array, actually 2 arrays one with all f string
s and one with all % strings.
To me it makes more sense to use a hash b/c each F string needs to be
pulled with its associative n% string.
This is why I want to populate a hash of arrays.

Would another strategy be easier and more efficient to fulfill this
requirement?

* If the format of all your data lines is "consistent", you could use split
on s+ to get the data fields instead of a tr/m cascade.

* Then, if I understand you correctly, you wantto build a hash with % keys
and F... values. This could be done with code like

push @{$lookup_hash{$pct_value}}, $F_value;

eventually, you even want a 2nd level hash with the F field number as key,
if the F values are unique over the whole file and the last field alway
begins with an F.

Or am I overlooking something?


ok, here some code (you have to adapt it to your needs):

=== test5.pl ===
#!/usr/bin/perl

use warnings; use strict;

my @lines=split "n", <<EOF;
1 2005/01/20 15:39 17 2% -il-o-b----- sg F01000
2 2005/01/20 15:53 14 1% -il-o-b----- sg F01001
3 2005/01/18 09:53 2 0% -il-o-b----- sg F01002
4 2005/02/04 16:41 196 100% -il-o-b----f sg F01003
5 2005/02/05 21:13 305 100% -il-o-b----f sg F01004
EOF

my %lookup;
foreach (@lines) {
my @fields=split /s+/;
push @{$lookup{$fields[4]}}, $fields[7];
}

print join "n", map {$_.": ".(join ", ", @{$lookup{$_}})} sort {$a <=> $b}
keys %lookup;
print "n";
=== end test5 pl ===

This prints:

0%: F01002
1%: F01001
2%: F01000
100%: F01003, F01004

[...]

John W. Krahn
[Email Removed] wrote:
QUOTE
John,

the reg exp s <-+> ();
^
was changed to

y/sg//;;
y/-//d;
s{w+} ();
to exclude the spaces and use y... thx
why are thre operators y or tr more efficient since these operators do not
use pattern matching?

Originally I was using an array, actually 2 arrays one with all f string s
and one with all % strings.
To me it makes more sense to use a hash b/c each F string needs to be
pulled with its associative n% string.
This is why I want to populate a hash of arrays.

Below is what is should of read for my population of the hash.

$HoA{$i++} = (split)[-1] if (m/f01(d+)(d+%) /gi  );

I feel like I've been banging my head against a brick wall the last few days.
I wonder if it will feel better if I stop. I think I will find out.


John
--
use Perl;
program
fulfillment

John W. Krahn
John Doe wrote:
QUOTE
Am Montag, 2. Mai 2005 03.49 schrieb [Email Removed]:

John,

the reg exp s <-+> ();
^
was changed to

y/sg//;;
y/-//d;
s{w+} ();
to exclude the spaces and use y... thx
why are thre operators y or tr more efficient since these operators do not
use pattern matching?

Don't know the internal details, but tr needs no backtracking, capturing and
such, it can simply take a char after the other and replace it with another
one. So the implementation of the algorithm must be much much easier.

tr/// does not use regular expressions and does not interpolate variables
because it is only evaluated at compile time therefore it has less overhead
then m// and s///.

perldoc perlop

[snip]

Because the transliteration table is built at compile time, neither
the SEARCHLIST nor the REPLACEMENTLIST are subjected to double
quote interpolation. That means that if you want to use variables,
you must use an eval():



John
--
use Perl;
program
fulfillment

QUOTE
* If the format of all your data lines is "consistent", you could use
split
on s+ to get the data fields instead of a tr/m cascade.

* Then, if I understand you correctly, you wantto build a hash with %
keys
and F... values. This could be done with code like

push @{$lookup_hash{$pct_value}}, $F_value;

eventually, you even want a 2nd level hash with the F field number as
key,
if the F values are unique over the whole file and the last field alway
begins with an F.


=== test5.pl ===
#!/usr/bin/perl

use warnings; use strict;

my @lines=split "n", <<EOF;
1 2005/01/20 15:39 17 2% -il-o-b----- sg F01000
2 2005/01/20 15:53 14 1% -il-o-b----- sg F01001
3 2005/01/18 09:53 2 0% -il-o-b----- sg F01002
4 2005/02/04 16:41 196 100% -il-o-b----f sg F01003
5 2005/02/05 21:13 305 100% -il-o-b----f sg F01004
EOF

my %lookup;
foreach (@lines) {
my @fields=split /s+/;
push @{$lookup{$fields[4]}}, $fields[7];
}

print join "n", map {$_.": ".(join ", ", @{$lookup{$_}})} sort {$a <=> $b}

keys %lookup;
print "n";
=== end test5 pl ===

This prints:

0%: F01002
1%: F01001
2%: F01000
100%: F01003, F01004

++++++++++++++++++++++++++++++++

ok thank you, but a few questions:

1) In programming Perl, it states one cannot push or pop a hash on page 10
paragraph 2. "You cannot push or pop a has b/c it does not make sense; a
hash has no beginning nor end." Why does Oreilly's PP 3rd edition say
this? It looks like you are pushing data elements from @lines into
%lookup, correct?

2) Is this : print join "n", map {$_.": ".(join ", ", @{$lookup{$_}})}
sort {$a <=> $b}
stating for every $_ construct or default variable, join newline to a
map of : any character with a comma then space then the data elements
from $lookup
sorted.

3) I know I can populate an array like so: my (@array, $i ) = (); forech
(<FH>) { $array[$i++] }
As an example, is it incorrect to do likewise to a hash as so:
my %HoA = ();
for (<FH> ) {
$HoA{$i++} = (split)[-1]
}
4) for my $d (keys %HoA) {
print "$d: @{$HoA{$d} }n";
}

This was from copied from programming perl and strict did not complain
and prints out the hash values. Is there a better way?



thxx...


derek

John Doe
Am Dienstag, 3. Mai 2005 03.30 schrieb [Email Removed]:
QUOTE
* If the format of all your data lines is "consistent", you could use

split

on s+ to get the data fields instead of a tr/m cascade.

* Then, if I understand you correctly, you wantto build a hash with %

keys

and F... values. This could be done with code like

push @{$lookup_hash{$pct_value}}, $F_value;

eventually, you even want a 2nd level hash with the F field number as

key,

if the F values are unique over the whole file and the last field alway
begins with an F.

=== test5.pl ===
#!/usr/bin/perl

use warnings; use strict;

my @lines=split "n", <<EOF;
1    2005/01/20 15:39  17  2%  -il-o-b-----  sg F01000
2    2005/01/20 15:53  14  1%  -il-o-b-----  sg F01001
3    2005/01/18 09:53    2  0%  -il-o-b-----  sg F01002
4    2005/02/04 16:41  196 100%  -il-o-b----f  sg F01003
5    2005/02/05 21:13  305 100%  -il-o-b----f  sg F01004
EOF

my %lookup;
foreach (@lines) {
my @fields=split /s+/;
push @{$lookup{$fields[4]}}, $fields[7];
}

print join "n", map {$_.": ".(join ", ", @{$lookup{$_}})} sort {$a <=> $b}

keys %lookup;
print "n";
=== end test5 pl ===

This prints:

0%: F01002
1%: F01001
2%: F01000
100%: F01003, F01004

++++++++++++++++++++++++++++++++

ok thank you, but a few questions:

1) In programming Perl, it states one cannot push or pop a hash on page 10
paragraph 2.  "You cannot push or pop a has b/c it does not make sense; a
hash has no beginning nor end."

True :-)

QUOTE
Why does Oreilly's PP 3rd edition say this?

Hm... because its true :-))

QUOTE
It looks like you are pushing data elements from @lines into
%lookup, correct?

(Please bear with my english while I try to explain...)

The data structure built in the foreach loop looks like

my %lookup=(
key1 =>
['val1a', 'val1b'] # etc. - note A
key2 =>
['val2a', 'val2b'] # etc. - note B
)

This means that key1 and key2 are (ordinary) hash keys, and the lines
commented with "note A/B" are (nearly ordinary) scalar values: The scalars
are not "123" or "string", but arrayrefs (which are, like all refs, scalar
values).

The push is done at the end of these _dereferenced_ arrayrefs (read: the
arrays). These arrays are initialized automagically at the time of the first
push to them.

The dereferencing is done by the '@{}' in

push @{ $lookup{$fields[4]} },
$fields[7];

while
$lookup{$fields[4]}

itself is the reference to the array (read: an arrayref).


QUOTE
2)  Is this :  print join "n", map {$_.": ".(join ", ", @{$lookup{$_}})}
sort {$a <=> $b}

stating

for every $_ construct or default variable,

No, you did not cite the part "keys %lookup;"


QUOTE
join newline to a
map of  :  any character with a comma then space then the data elements
from $lookup
sorted.

I add some formatting to explain. It's best understood if read backwards, from
"keys %lookup" to "print"; imagine the execution flow in this direction:

print join "n",
map {
$_ .
": " .
( join ", ", @{$lookup{$_}} )
}
sort {$a <=> $b}
keys %lookup;

"Take the keys from %lookup into $_, then sort $_ numerically, then use a
map{} to format a string of every single hash key (in $_) and the
corresponding array elements accessed via the 'scalar arrayref hash
value' (again, @{} dereferences the arrayref). The map results in a string
for every $_. These are concatenated by a newline and printed.

This could be written the long way (but now to be read topdown):

my @keys=keys %lookup;
my @sorted_keys=sort {$a <=> $b} @keys;
my @per_key_strings;
foreach my $k (@sorted_keys) {
push @per_key_strings,
$k . ": " . ( join ", ", @{$lookup{$_}} );
}
print join "n", @per_key_strings;


QUOTE
3) I know I can populate an array like so:
my (@array, $i )  = ();

my (@array, $i);

or, for clarity:

my @array; # no need to initialize with ()
my $i=0; # explicitly state start value

QUOTE
foreach
(<FH>) { $array[$i++] }

What's the sense of it since you don't assign any array element?

QUOTE
As an example, is it incorrect to do likewise to a hash as so:
my %HoA = ();
for (<FH> ) {
$HoA{$i++} = (split)[-1]
}

Looks correct to me. If I wanted to be shure, I would run the code and then
inspect the resulting data structure :-)

But, as somebody else already mentioned, it makes not much sense to use a hash
with keys from 0..n, this could be done with an array containing elements
0..n.

QUOTE
4)  for my $d (keys %HoA) {
print "$d: @{$HoA{$d} }n";

Maybe the @{} here confuses in combination with above @{} that was used to
"intentionally" dereference a scalar arrayref.

Here, @{} is a common way to interpolate one or more data elements into a
string - also by dereferencing an arrayref which is formed by the value(s) -
in most cases just one - within the @{}.

QUOTE
}

This was from copied from programming perl and strict did not complain
and prints out the hash values.  Is there a better way?

I don't think so. But there are other ways to do it, for instance, avoiding
@{},

print "$d: ", $HoA{$d}, "n";



I must admit that I had big problems with the english, maybe I missed the
overview of your question(s), but hope it was understandable.

joe.

John,
I am a lotus user so my top-down reply is default ...sorry.


I think all looks good, but I have to ask why are you initializing an array
to hold values of a hash with keys?

This could be written the long way (but now to be read
topdown):
my @keys=keys %lookup;
my @sorted_keys=sort {$a <=> $b} @keys;
my @per_key_strings;
foreach my $k (@sorted_keys) {
push @per_key_strings,
$k . ": " . ( join ", ", @{$lookup{$_}} );
}
print join "n", @per_key_strings;

My whole purpose was to populate a hash like so:

my %hash = {

F01000 => '0%',
F01001 => '10%',
F01002 => '100%',
};

If one cannot and should not push a hash, then what is the ideal way to
populate a hash..... like so?
for ( <FH>) {
for my $d (keys %HoA) {
print "$d: @{$HoA{$d} }n";
}
}

OR
my %HoA = ();
for (<FH> ) {
$HoA{$i++} = (split)[-1]
}
????

thx again...derek




John Doe
<security.departm
[Email Removed]> To
[Email Removed]
05/03/2005 12:37 cc
AM
Subject
Re: populating a hash with % used
as the key and F string as the
value










Am Dienstag, 3. Mai 2005 03.30 schrieb [Email Removed]:
QUOTE
* If the format of all your data lines is "consistent", you could use

split

on s+ to get the data fields instead of a tr/m cascade.

* Then, if I understand you correctly, you wantto build a hash with %

keys

and F... values. This could be done with code like

push @{$lookup_hash{$pct_value}}, $F_value;

eventually, you even want a 2nd level hash with the F field number as

key,

if the F values are unique over the whole file and the last field alway
begins with an F.

=== test5.pl ===
#!/usr/bin/perl

use warnings; use strict;

my @lines=split "n", <<EOF;
1    2005/01/20 15:39  17  2%  -il-o-b-----  sg F01000
2    2005/01/20 15:53  14  1%  -il-o-b-----  sg F01001
3    2005/01/18 09:53    2  0%  -il-o-b-----  sg F01002
4    2005/02/04 16:41  196 100%  -il-o-b----f  sg F01003
5    2005/02/05 21:13  305 100%  -il-o-b----f  sg F01004
EOF

my %lookup;
foreach (@lines) {
my @fields=split /s+/;
push @{$lookup{$fields[4]}}, $fields[7];
}

print join "n", map {$_.": ".(join ", ", @{$lookup{$_}})} sort {$a <=
$b}

keys %lookup;
print "n";
=== end test5 pl ===

This prints:

0%: F01002
1%: F01001
2%: F01000
100%: F01003, F01004

++++++++++++++++++++++++++++++++

ok thank you, but a few questions:

1) In programming Perl, it states one cannot push or pop a hash on page
10
paragraph 2.  "You cannot push or pop a has b/c it does not make sense; a
hash has no beginning nor end."

True :-)

QUOTE
Why does Oreilly's PP 3rd edition say this?

Hm... because its true :-))

QUOTE
It looks like you are pushing data elements from @lines into
%lookup, correct?

(Please bear with my english while I try to explain...)

The data structure built in the foreach loop looks like

my %lookup=(
key1 =>
['val1a', 'val1b'] # etc. - note A
key2 =>
['val2a', 'val2b'] # etc. - note B
)

This means that key1 and key2 are (ordinary) hash keys, and the lines
commented with "note A/B" are (nearly ordinary) scalar values: The scalars
are not "123" or "string", but arrayrefs (which are, like all refs, scalar
values).

The push is done at the end of these _dereferenced_ arrayrefs (read: the
arrays). These arrays are initialized automagically at the time of the
first
push to them.

The dereferencing is done by the '@{}' in

push @{ $lookup{$fields[4]} },
$fields[7];

while
$lookup{$fields[4]}

itself is the reference to the array (read: an arrayref).


QUOTE
2)  Is this :  print join "n", map {$_.": ".(join ", ", @{$lookup{$_}})}
sort {$a <=> $b}

stating

for every $_ construct or default variable,

No, you did not cite the part "keys %lookup;"


QUOTE
join newline to a
map of  :  any character with a comma then space then the data elements
from $lookup
sorted.

I add some formatting to explain. It's best understood if read backwards,
from
"keys %lookup" to "print"; imagine the execution flow in this direction:

print join "n",
map {
$_ .
": " .
( join ", ", @{$lookup{$_}} )
}
sort {$a <=> $b}
keys %lookup;

"Take the keys from %lookup into $_, then sort $_ numerically, then use a
map{} to format a string of every single hash key (in $_) and the
corresponding array elements accessed via the 'scalar arrayref hash
value' (again, @{} dereferences the arrayref). The map results in a string
for every $_. These are concatenated by a newline and printed.

This could be written the long way (but now to be read topdown):

my @keys=keys %lookup;
my @sorted_keys=sort {$a <=> $b} @keys;
my @per_key_strings;
foreach my $k (@sorted_keys) {
push @per_key_strings,
$k . ": " . ( join ", ", @{$lookup{$_}} );
}
print join "n", @per_key_strings;


QUOTE
3) I know I can populate an array like so:
my (@array, $i )  = ();

my (@array, $i);

or, for clarity:

my @array; # no need to initialize with ()
my $i=0; # explicitly state start value

QUOTE
foreach
(<FH>) { $array[$i++] }

What's the sense of it since you don't assign any array element?

QUOTE
As an example, is it incorrect to do likewise to a hash as so:
my %HoA = ();
for (<FH> ) {
$HoA{$i++} = (split)[-1]
}

Looks correct to me. If I wanted to be shure, I would run the code and then

inspect the resulting data structure :-)

But, as somebody else already mentioned, it makes not much sense to use a
hash
with keys from 0..n, this could be done with an array containing elements
0..n.

QUOTE
4)  for my $d (keys %HoA) {
print "$d: @{$HoA{$d} }n";

Maybe the @{} here confuses in combination with above @{} that was used to
"intentionally" dereference a scalar arrayref.

Here, @{} is a common way to interpolate one or more data elements into a
string - also by dereferencing an arrayref which is formed by the value(s)
-
in most cases just one - within the @{}.

QUOTE
}

This was from copied from programming perl and strict did not
complain
and prints out the hash values.  Is there a better way?

I don't think so. But there are other ways to do it, for instance, avoiding

@{},

print "$d: ", $HoA{$d}, "n";



I must admit that I had big problems with the english, maybe I missed the
overview of your question(s), but hope it was understandable.

joe.

--
To unsubscribe, e-mail: [Email Removed]
For additional commands, e-mail: [Email Removed]
<http://learn.perl.org/> <http://learn.perl.org/first-response>

John Doe
Am Dienstag, 3. Mai 2005 23.42 schrieb [Email Removed]:
QUOTE
John,
I am a lotus user so my top-down reply is default ...sorry.

Don't know Lotus. No possibilities to change defaults there? ;-)

QUOTE
I think all looks good, but I have to ask why are you initializing an array
to hold values of a hash with keys?

Because you wrote in your question:

| I was thinking of using a hash of arrays b/c I want to look-up each array
| by a certain string and that string would the % string.| [...]

which, even after rereading it, says that you want
a) to lookup something _by_ the % string, and that means the % string must be
the hash key,
b) to lookup arrays, which means the hash values are multi valued

and

| Here is the data file:
|
| 1 2005/01/20 15:39 17 2% -il-o-b----- sg F01000
| 2 2005/01/20 15:53 14 1% -il-o-b----- sg F01001
| 3 2005/01/18 09:53 2 0% -il-o-b----- sg F01002
| 4 2005/02/04 16:41 196 100% -il-o-b----f sg F01003
| 5 2005/02/05 21:13 305 100% -il-o-b----f sg F01004

the % string is not unique over data file, whereas the F... string looks like
being unique.

and

because it seemed to make sense for me looking up the data by the pct value.


QUOTE
My whole purpose was to populate a hash like so:

my %hash = {

F01000 => '0%',
F01001 => '10%',
F01002 => '100%',
};

If one cannot and should not push a hash, then what is the ideal way to
populate a hash..... like so?
for ( <FH>) {
for my $d (keys %HoA) {
print "$d: @{$HoA{$d} }n";
}
}

OR
my %HoA = ();
for (<FH> ) {
$HoA{$i++} = (split)[-1]
}

Since only the second snippet populates a hash, I'd say the second is better.



joe

[snipped the rest to prevent combined top/inline posting reordering time]

Shiping Wang
try this:

ppm install http://theoryx5.uwinnipeg.ca/ppms/GD.ppd

Good luck!

At 02:14 PM 5/4/2005, Mark Cohen wrote:

QUOTE
Hello,
When looking for the GD package under Windows using PPM i can't find the
package.
I try using the install GD but it tells me that that the package doesn't
exist.
The ppm version is 3.1
The repositories are:
1)Activestate PP2 repository
2)Activestate package repository

What could be the reason ?

Thanks Mark


--
To unsubscribe, e-mail: [Email Removed]
For additional commands, e-mail: [Email Removed]
<http://learn.perl.org/> <http://learn.perl.org/first-response


Siegfried Heintze
Wow! Thanks for the enthusiastic responses!

Well I'm a C++ guy so GTK* and WxWindows look good. But is anyone using
these on ActiveState Perl? Is there some other perl for windows that I
should be using for GUI?

Siegfried



QUOTE

-----Original Message----->From: Daniel Kasak
[mailto:[Email Removed]]
Sent: Thursday, May 05, 2005 5:20 AM>To: Siegfried Heintze; 'Perl Beginners
List'>Subject: Re: Favorite Packages for Platform Neutral GUI?

Siegfried Heintze wrote:

I get the impression that there are several alternatives to use=ing Tk for
writing OS neutral GUI programs in Perl.

Can anyone point me to a discussion that might help me choose one?


I'll give my vote to Gtk2 any day.

To start with, Tk looks like barf. It really, really, looks bad. Gtk2
has a large selection of widgets and excellent theming support. If you
want people to smile when your application starts instead of frowning,
use Gtk2. For Linux users, you have the added bonus of your application
looking like the rest of their Gtk2 applications.

Next, Gtk2 is being actively developed. While I don't have any on-depth
knowledge of Tk, my impression is that it's pretty static.

While I concede that there are probably more users of Perl-Tk than
Gtk2-Perl, the support in the Gtk2-Perl forum is excellent. As for bugs,
I've only ever stumbled across *one* bug, and it was fixed months before
I came across it ... I just hadn't updated yet.

OS support is pretty good for Gtk2. It obviously works well on Linux.
There are installers for Gtk-2.6.7 ( or something like that ) for
Windows, with a bundled theme switcher and a large selection of themes.
Gtk2 works well under Windows - not quite as fast as under Linux, but
otherwise I haven't hit any bugs. OS-X users can use Fink to install
Gtk2. One of the Gtk2-Perl uses a Powerbook as a development box. I also
have a Powerbook, but I use Darwin Ports, and their Gtk2 ports aren't
quite as good as Fink. I will be moving to Fink soon ... but anyway,
*apparently* it works perfectly well if you install via fink. OS-X users
will also have to be running an X server, which slows things down a bit.
Unfortunately there's no native port of Gtk2 for OS-X.

Glade ( the Gtk2 WYSIWYG builder ) is also a pleasure to work with.

As you might guess, I like Gtk2-Perl. I'm porting our database
front-ends from MS Access to Gtk2-Perl at work. I have 2 systems
complete rolled out, and I'm immensely happy with the results. I wrote
Gtk2::Ex::DBI ( see http://entropy.homelinux.org ... which is a little
broken after a botched php upgrade, but still usable ... or fetch via
cpan ) to bind a DBI recordset to widgets on a Glade-generated form.

Anyway, enough of Gtk2 :) There's also Perl-QT. I looked at it briefly
before choosing Gtk2-Perl. I simply don't like QT and it's themes. I
don't run KDE and don't pay too much attention to what they're doing. QT
has been ported to a lot of systems, including Windows and OS X. I'm not
sure how easy it would be to get the Perl bindings compiled or whether
there are binary packages available.

So back to Gtk2. Use it. It rocks.

Dan


John Moon
Subject: Re: How to turn $_ into a hashref?

Philip, thank you very much. I overlooked the meaning of the second variable
to selectrow_array entirely.

Two follow up questions:
1. If I don't need or want DBI handle attributes (I'm happy with the
defaults, for instance), how can I define a null hash reference?
2. I chose selectrow_array specifically because I didn't need the
prepare/execute/fetch routine. The query result is either a) the author is
already in the table, and I want the record id number, or b) the author
isn't in the table, and I'm going to add the name and then find the record
id number of the record just added. There should never be more than one
matching author name in the table, so I didn't think I needed a fetch
capable of multiple rows. You're suggesting I look at fetchrow_array(). Am I
overlooking something that you're aware of?

Thanks, again, for your help.

-Kevin

QUOTE
"Philip M. Gollucci" <[Email Removed]> 05/05/05 03:38PM
KEVIN ZEMBOWER wrote:


QUOTE
I'm using a function from DBI that needs a hash reference according to the
documentation, and I don't know how to turn $_ into one. The section of code

I have is:
QUOTE
if ($record{"Author"}) {
my @indfields = split(/|/, $record{"Author"});
foreach (@indfields) {
my $authorid = $dbh->selectrow_array("SELECT authorid FROM author
WHERE name = ?", $_)
or die "Can't execute statement: $DBI::errstr";




perldoc DBI


The second argument to this is a hashref of DBI handle attributes not
the bind values

you want:

$dbh->selectrow_array($sql, %db_attrs, ($_));

somewhere above:
our %db_attrs = (
RaiseError => 1,
PrintError => 0,
AutoCommit => 1,
Taint => 1
......
);

Also, the how point of using bind values is you should $dbh->prepare()
your query outside of the loop.

then $sth->execute($_) in the loop.

and $sth->finish() after the loop.

Check out $sth->fetchrow_arrary() instead.

HTH

--
END
----------------------------------------------------------------------------

Well looking at your code ... right before the DBI call you do a
"foreach"... That would indicate, to me, that you "expected" to "fetch"
more than one row... but if you truly expect to only fetch one row then yes,
do the selectrow_array. But if not...

The DBI "prepare" function is "similar" to declaring a cursor in PLSql then
you only "pay once" to parse the SQL... The execute is "like" the PLSql open
of a cursor... and the fetchrow_array is "like" fetch cursor into
statement...

I also like very much the DBI functions selectall_arrayref and
selectall_hashref function for one time small sets/subsets of data.

This is a really nice package with lots of ways to do the same thing
different ways given different circumstances. Choose what is best for you...

jwm

John Moon
Subject: transform array into hash

Hi all,

just easy question, here is too much hours and my brain doesn't work
any more. How to transform array into hash ?

my @array = 1..4;

I want to have:
%hash = ( one => 1, two => 2, three => 3, four => 4 );

tried something like this, but it doesnt work:
my $hash{qw/one two three four/} = (1..4);

Anyone?

Obviously you have more than 4 items(?)...

What do you have? What do you want/have for keys and what do you want/have
for values?

jwm

Daniel Kasak
Siegfried Heintze wrote:

QUOTE
Wow! Thanks for the enthusiastic responses!

Well I'm a C++ guy so GTK* and WxWindows look good. But is anyone using
these on ActiveState Perl? Is there some other perl for windows that I
should be using for GUI?

Siegfried



ActiveState Perl is fine for Gtk2-Perl.

At least it works fine while it's running. For some reason I get a crash
on exiting apps under Windows, but never while the app is actually
running. I've never bothered chasing it down, and I'm a little
suspicious it may be Gtk2's fault anyway. You will need to use the Glade
GUI builder ( and Gtk2::GladeXML to build your GUI from your Glade
project files ).

Dan

Macromedia
Something like this?

#!/usr/bin/perl -w

#Syntax: test.pl "<directory>" "<match>"

require 5.000;
use strict;

# Pass filename parameter
my $path = $ARGV[0];
my $num = $ARGV[1];

while ($line = <$path*.txt>) {
open (FILE, $line) or die "cannot open $line: $!n";
while (<FILE>) {
if ($line =~ /$num/ {
print $line;
}
}
close FILE;
}



-----Original Message-----
From: Gavin Henry [mailto:[Email Removed]]
Sent: Friday, May 06, 2005 11:24 AM
To: [Email Removed]
Subject: Re: Writing my first perl script

<quote who="macromedia">
QUOTE

Hello,

I'm not sure about the login or how I should approach what I want to
achieve. I require a script that does the following.

Here are the quick answer, which provide you some reading material:

QUOTE

1. Search a directory and all sub-directories for a certain file
extension. (Ex. .txt)

If you are famliar with the Unix find command, you can use find2perl;;

http://perldoc.perl.org/find2perl.html

QUOTE

2. Get the results of the above search and check "inside" each file
for
a string match. (Ex. "123").
QUOTE

3. List the matches found into an external file for further
processing.


See above.

QUOTE
What features should I be looking at to achieve this? Anyone know of
some good examples that I could pick away at?


See above.

QUOTE





--
To unsubscribe, e-mail: [Email Removed]
For additional commands, e-mail: [Email Removed]
<http://learn.perl.org/> <http://learn.perl.org/first-response





--
To unsubscribe, e-mail: [Email Removed]
For additional commands, e-mail: [Email Removed]
<http://learn.perl.org/> <http://learn.perl.org/first-response>

Gavin Henry
On Friday 06 May 2005 16:50, macromedia wrote:
QUOTE
Something like this?

#!/usr/bin/perl -w

#Syntax: test.pl "<directory>" "<match>"

require 5.000;
use strict;

# Pass filename parameter
my $path = $ARGV[0];
my $num = $ARGV[1];

while ($line = <$path*.txt>) {
open (FILE, $line) or die "cannot open $line: $!n";
while (<FILE>) {
if ($line =~ /$num/ {
print $line;
}
}
close FILE;
}


Looks good. Does it work?

QUOTE

-----Original Message-----
From: Gavin Henry [mailto:[Email Removed]]
Sent: Friday, May 06, 2005 11:24 AM
To: [Email Removed]
Subject: Re: Writing my first perl script

<quote who="macromedia"

Hello,

I'm not sure about the login or how I should approach what I want to
achieve. I require a script that does the following.

Here are the quick answer, which provide you some reading material:
1. Search a directory and all sub-directories for a certain file
extension. (Ex. .txt)

If you are famliar with the Unix find command, you can use find2perl;;

http://perldoc.perl.org/find2perl.html

2. Get the results of the above search and check "inside" each file

for

a string match. (Ex. "123").

You would use a while loop,  Filehandle and some regular expressions:

http://perldoc.perl.org/perlopentut.html
http://perldoc.perl.org/perlrequick.html
http://perldoc.perl.org/perlfaq5.html

3. List the matches found into an external file for further

processing.

See above.

What features should I be looking at to achieve this? Anyone know of
some good examples that I could pick away at?

See above.

--
To unsubscribe, e-mail: [Email Removed]
For additional commands, e-mail: [Email Removed]
<http://learn.perl.org/> <http://learn.perl.org/first-response

--
To unsubscribe, e-mail: [Email Removed]
For additional commands, e-mail: [Email Removed]
<http://learn.perl.org/> <http://learn.perl.org/first-response

--
Just getting into the best language ever...
Fancy a [Email Removed] or something
on http://www.perl.me.uk Just ask!!!

Macromedia
not quite. Getting these errors...

perl test.pl "d:/mywork/" "123"

Global symbol "line" requires explicit package name at test.pl line 12.
Variable "$line" is not imported at test.pl line 13.
Global symbol "line" requires explicit package name at test.pl line 13.
Variable "$line" is not imported at test.pl line 13.
Global symbol "line" requires explicit package name at test.pl line 13.
Variable "$line" is not imported at test.pl line 15.
Global symbol "line" requires explicit package name at test.pl line 15.
Variable "$line" is not imported at test.pl line 16.
Global symbol "line" requires explicit package name at test.pl line 16.
syntax error at test.pl line 17, near "}"
syntax error at test.pl line 20, near "}"
Execution of test.pl aborted due to compilation errors.


-----Original Message-----
From: Gavin Henry [mailto:[Email Removed]]
Sent: Friday, May 06, 2005 12:24 PM
To: [Email Removed]
Subject: Re: Writing my first perl script

On Friday 06 May 2005 16:50, macromedia wrote:
QUOTE
Something like this?

#!/usr/bin/perl -w

#Syntax: test.pl "<directory>" "<match>"

require 5.000;
use strict;

# Pass filename parameter
my $path = $ARGV[0];
my $num = $ARGV[1];

while ($line = <$path*.txt>) {
open (FILE, $line) or die "cannot open $line: $!n";
while (<FILE>) {
if ($line =~ /$num/ {
print $line;
}
}
close FILE;
}


Looks good. Does it work?

QUOTE

-----Original Message-----
From: Gavin Henry [mailto:[Email Removed]]
Sent: Friday, May 06, 2005 11:24 AM
To: [Email Removed]
Subject: Re: Writing my first perl script

<quote who="macromedia"

Hello,

I'm not sure about the login or how I should approach what I want to
achieve. I require a script that does the following.

Here are the quick answer, which provide you some reading material:
1. Search a directory and all sub-directories for a certain file
extension. (Ex. .txt)

If you are famliar with the Unix find command, you can use find2perl;;

http://perldoc.perl.org/find2perl.html

2. Get the results of the above search and check "inside" each file

for

a string match. (Ex. "123").

You would use a while loop,  Filehandle and some regular expressions:

http://perldoc.perl.org/perlopentut.html
http://perldoc.perl.org/perlrequick.html
http://perldoc.perl.org/perlfaq5.html

3. List the matches found into an external file for further

processing.

See above.

What features should I be looking at to achieve this? Anyone know of
some good examples that I could pick away at?

See above.

--
To unsubscribe, e-mail: [Email Removed]
For additional commands, e-mail: [Email Removed]
<http://learn.perl.org/> <http://learn.perl.org/first-response

--
To unsubscribe, e-mail: [Email Removed]
For additional commands, e-mail: [Email Removed]
<http://learn.perl.org/> <http://learn.perl.org/first-response

--
Just getting into the best language ever...
Fancy a [Email Removed] or something
on http://www.perl.me.uk Just ask!!!

--
To unsubscribe, e-mail: [Email Removed]
For additional commands, e-mail: [Email Removed]
<http://learn.perl.org/> <http://learn.perl.org/first-response>

Michael Gale
Hello,

A bash script would be a better choice for this particular request.

#!/bin/bash

find . -type f -name "*.txt" -print | xargs grep -l 123 >> externalfile

The above command would search the current directory plus all sub-
directories for all files the end in a ".txt" and search each file for
the string "123" and list the resulted files names in the file
"externalfile"


Michael


On Fri, 2005-05-06 at 11:11 -0400, macromedia wrote:
QUOTE
Hello,

I'm not sure about the login or how I should approach what I want to
achieve. I require a script that does the following.

1. Search a directory and all sub-directories for a certain file
extension. (Ex. .txt)

2. Get the results of the above search and check "inside" each file for
a string match. (Ex. "123").

3. List the matches found into an external file for further processing.

What features should I be looking at to achieve this? Anyone know of
some good examples that I could pick away at?

Josh






Ing. Branislav Gerzo
amr [a], on Saturday, May 7, 2005 at 16:13 (-0700) thinks about:

a> I try the pop and it does the job but I think there is another way?

here are some examples comes to my mind:

use strict;
use warnings;

my @list = 1 .. 10;

print $list[-1], "n";
print $list[$#list], "n";
print $list[@list-1], "n";
print pop @list, "n";

--

...m8s, cu l8r, Brano.

[I am Bob Vila of Borg: This Old House is irrelevant.]

Ramprasad A Padmanabhan
On Sun, 2005-05-08 at 04:43, amr wrote:
QUOTE
How can I call the last element in the array?

I try the pop and it does the job but I think there is another way?



$array[-1]



HTH
Ram


----------------------------------------------------------
Netcore Solutions Pvt. Ltd.
Website: http://www.netcore.co.in
Spamtraps: http://cleanmail.netcore.co.in/directory.html
----------------------------------------------------------

Ricardo SIGNES
* amr <[Email Removed]> [2005-05-07T19:45:56]
QUOTE
Thanks it was very useful.
Now, I need to do the same with sorted hash array. Can I?

"sorted hash array" is not clear, to me. Do you mean you've done this:
sort keys %hash
?

If so, just reverse the sort and use the first element, or assign to an
array and use element -1 as in previous mails.

--
rjbs

Bright True
$array[-1]

On 5/7/05, amr <[Email Removed]> wrote:
QUOTE

How can I call the last element in the array?

I try the pop and it does the job but I think there is another way?



Ing. Branislav Gerzo
amr [a], on Saturday, May 7, 2005 at 16:45 (-0700) typed the
following:

a> Now, I need to do the same with sorted hash array. Can I?

you can do everything. But give us example of source data dump.

--

...m8s, cu l8r, Brano.

[Home: A place teenagers stay while the car is repaired.]

Gavin Henry
On Sunday 08 May 2005 00:13, amr wrote:
QUOTE
How can I call the last element in the array?

I try the pop and it does the job but I think there is another way?


Of course, TMTOWTDI (http://catb.org/~esr/jargon/html/T/TMTOWTDI.html)

$ARRAY[$#ARRAY--]

See:

http://perldoc.perl.org/functions/pop.html

But, if you know how many items you have in your array, you can call it:

$array[last_item]

where last item is the number/item you want minus one.

If this is unclear, just say and I will explain it a bit more.

--
Walking the road to enlightenment... I found a penguin and a camel on the
way.....
Fancy a [Email Removed]? Just ask!!!

John W. Krahn
Gavin Henry wrote:
QUOTE
On Sunday 08 May 2005 00:13, amr wrote:

How can I call the last element in the array?

I try the pop and it does the job but I think there is another way?

Of course, TMTOWTDI (http://catb.org/~esr/jargon/html/T/TMTOWTDI.html)

$ARRAY[$#ARRAY--]

Oh wow. Did you try that? You do realise that modifying $#ARRAY changes the
size of @ARRAY?

$ perl -le'
@ARRAY = "A" .. "Z";
print "Size: " . @ARRAY, " $ARRAY[$#ARRAY]";
print "Size: " . @ARRAY, " $ARRAY[$#ARRAY--]";
print "Size: " . @ARRAY, " $ARRAY[$#ARRAY--]";
print "Size: " . @ARRAY, " $ARRAY[--$#ARRAY]";
print "Size: " . @ARRAY, " $ARRAY[--$#ARRAY]";
'
Size: 26 Z
Size: 26
Size: 25
Size: 24 W
Size: 23 V



John
--
use Perl;
program
fulfillment

Gavin Henry
On Saturday 07 May 2005 20:56, John W. Krahn wrote:
QUOTE
Gavin Henry wrote:
On Sunday 08 May 2005 00:13, amr wrote:
How can I call the last element in the array?

I try the pop and it does the job but I think there is another way?

Of course, TMTOWTDI (http://catb.org/~esr/jargon/html/T/TMTOWTDI.html)

$ARRAY[$#ARRAY--]

Oh wow.  Did you try that?  You do realise that modifying $#ARRAY changes
the size of @ARRAY?

Yes, this was my misunderstanding of the OP question. He wants to only find
out what is the last element of the array and not modify it, but I gave the
equivalent of the pop command, which your proof demonstrates.

http://perldoc.perl.org/functions/pop.html

QUOTE

$ perl -le'
@ARRAY = "A" .. "Z";
print "Size: " . @ARRAY, " $ARRAY[$#ARRAY]";
print "Size: " . @ARRAY, " $ARRAY[$#ARRAY--]";
print "Size: " . @ARRAY, " $ARRAY[$#ARRAY--]";
print "Size: " . @ARRAY, " $ARRAY[--$#ARRAY]";
print "Size: " . @ARRAY, " $ARRAY[--$#ARRAY]";
'
Size: 26 Z
Size: 26
Size: 25
Size: 24 W
Size: 23 V



John
--
use Perl;
program
fulfillment

--
Walking the road to enlightenment... I found a penguin and a camel on the
way.....
Fancy a [Email Removed]? Just ask!!!

Charles K. Clarkson
Ricardo SIGNES <mailto:[Email Removed]> wrote:

: * amr <[Email Removed]> [2005-05-07T19:45:56]
: : Thanks it was very useful.
: : Now, I need to do the same with sorted hash array. Can I?
:
: "sorted hash array" is not clear, to me. Do you mean you've done
: this: sort keys %hash
: ?
:

my %foo = 'a' .. 'h';


: If so, just reverse the sort and use the first element,

print + (reverse sort keys %foo )[0];


: or assign to an array and use element -1 as in previous mails.


my @foo = sort keys %foo;
print $foo[-1];

Or:

print + (sort keys %foo )[-1];


HTH,

Charles K. Clarkson
--
Mobile Homes Specialist


Peter Rabbitson
On Sat, May 07, 2005 at 04:13:12PM -0700, amr wrote:
QUOTE
How can I call the last element in the array?

I try the pop and it does the job but I think there is another way?


If
my @a = (1, 2, 3, 4);
then:

my $last = pop @a;
is the same as
my $last = $a[-1];

and

pop @a;
my $third = pop @a;
is the same as
my $third = $a[-2];

The negative sign in front of N means go N positions towards the start of
the array from the end.

Peter

Amr
Thanks it was very useful.

Now, I need to do the same with sorted hash array. Can I?



Thanks

Amr



-----Original Message-----
From: Ing. Branislav Gerzo [mailto:[Email Removed]]
Sent: Saturday, May 07, 2005 6:16 AM
To: [Email Removed]
Subject: Re: The last element



amr [a], on Saturday, May 7, 2005 at 16:13 (-0700) thinks about:



a> I try the pop and it does the job but I think there is another way?



here are some examples comes to my mind:



use strict;

use warnings;



my @list = 1 .. 10;



print $list[-1], "n";

print $list[$#list], "n";

print $list[@list-1], "n";

print pop @list, "n";



--



...m8s, cu l8r, Brano.



[I am Bob Vila of Borg: This Old House is irrelevant.]







--

To unsubscribe, e-mail: [Email Removed]

For additional commands, e-mail: [Email Removed]

<http://learn.perl.org/> <http://learn.perl.org/first-response>

Chris
Greetings,

We have written a web application utilizing mod_perl and MySQL. We have also
written testing scripts using WWW::Mechanize that simulate a user. These
scripts were first developed as test scripts to ensure actions were performed
correctly, etc.

We would now like to take these scripts and use them in order to benchmark the
machines the software runs on to get estimates of the max utilization for a
certain setup.

Each feature of the software has its own testing script which is broken down
into individual subroutines to simulate actions, then different "profiles"
call the various subroutines to check all areas of functionality. This
simulates a single user per execution of the script.

We would like to be able to create a "master" test script that ties all these
together, which we can control the number of times a "profile" is executed,
etc.

The only way I can explain it would be something pseudo code like:

(in a required module)
sub user_signup {
get_page
sleep 5
fill form
submit
}

sub user_checkstats {
get page
sleep 1
fill form
submit
}

I would like to be able to do something like:

(in the master script)
sub profile_one {
user_signup();
user_checkstats();
}

and not have to wait for user_signup() to complete for user_checkstats() to
execute?

I hope this makes sense, this is the best way i can explain it. I'm pretty
much trying to be able to simulate simultaneous users.

Any tips are appreciated!!

TapasranjanMohapatra
-----Original Message-----
From: N. Ganesh Babu [mailto:[Email Removed]]
Sent: Mon 5/9/2005 10:27 AM
To: Perl Beginners List
Subject: seek(FH, 0,0) not working

Dear All,

In the attached file, the date is present in the last line. My
requirement is to capture the date and fill it in the date field from
the line 1. after capturing the date through regular expression I am
using seek(FH,0,0) to goto the beginning of the file. But it has no effect.

My code is like this.

while($line=<FH>)
{
if($line=~m/Printed on Sat ([a-z]{3}s*d{1,2}s*d{4})/i)
{
$date=$1;
}
seek(FH,0,0)
$line=~s/|d{3}.................$date.............;
}

But this code is not giving the required result. Please help me in
solving this problem.

Regards,
Ganesh


Ganesh,
The substitution string is not proper. What you want to do? Just printing to STDOUT or writing to the file itself? If writing to file Have you opened the file for writing also?
If you dont need to process other lines of file, you should break from while loop and after that do a seek.
HTH
tapas

N. Ganesh Babu
Hi Mohapatra,

The idea of seek after while loop worked fine. Thanks for your help.

Regards,
Ganesh


TapasranjanMohapatra wrote:

QUOTE

-----Original Message-----
From: N. Ganesh Babu [mailto:[Email Removed]]
Sent: Mon 5/9/2005 10:27 AM
To: Perl Beginners List
Subject: seek(FH, 0,0) not working

Dear All,

In the attached file, the date is present in the last line. My
requirement is to capture the date and fill it in the date field from
the line 1. after capturing the date through regular expression I am
using seek(FH,0,0) to goto the beginning of the file. But it has no effect.

My code is like this.

while($line=<FH>)
{
if($line=~m/Printed on Sat ([a-z]{3}s*d{1,2}s*d{4})/i)
{
$date=$1;
}
seek(FH,0,0)
$line=~s/|d{3}.................$date.............;
}

But this code is not giving the required result. Please help me in
solving this problem.

Regards,
Ganesh


Ganesh,
The substitution string is not proper. What you want to do? Just printing to STDOUT or writing to the file itself? If writing to file Have you opened the file for writing also?
If you dont need to process other lines of file, you should break from while loop and after that do a seek.
HTH
tapas



FlashMX
Hi,

I have a Perl script that requires the following module to be installed.

use File::Find;

open(IN,$File::Find::name) or ...

WHen I ran the PPM and did a search for "Find" I couldn't find the module "File-Find"? Which one do I have to install?

This is what gets listed:

26. File-Find-Duplicates [0.05] Find duplicate files
27. File-Find-Duplicates [0.05] Find duplicate files
28. File-Find-Iterator [0.3] Iterator interface for search files
29. File-Find-Iterator [0.2] Iterator interface for search files
30. File-Find-Iterator [0.3] Iterator interface for search files
31. File-Find-Rule [0.28] Alternative interface to File::Find
32. File-Find-Rule [0.11] Alternative interface to File::Find
33. File-Find-Rule [0.21] Alternative interface to File::Find
34. File-Find-Rule [0.23] Alternative interface to File::Find
35. File-Find-Rule [0.24] Alternative interface to File::Find
36. File-Find-Rule [0.27] Alternative interface to File::Find
37. File-Find-Rule [0.28] Alternative interface to File::Find
38. File-Find-Rule-Dige~ [0.01] rules for matchig checksum
39. File-Find-Rule-Dige~ [0.01] rules for matchig checksum
40. File-Find-Rule-DIZ [0.05] Rule to match the contents of a FILE_ID.DIZ
41. File-Find-Rule-DIZ [0.01] Rule to match the contents of a FILE_ID.DIZ
42. File-Find-Rule-DIZ [0.04] Rule to match the contents of a FILE_ID.DIZ
43. File-Find-Rule-DIZ [0.05] Rule to match the contents of a FILE_ID.DIZ
44. File-Find-Rule-File~ [1.21] File::Find::Rule adapted to Filesys::Virtu~
45. File-Find-Rule-File~ [1.21] File::Find::Rule adapted to Filesys::Virtu~
46. File-Find-Rule-Imag~ [0.03] rules for matching image dimensions
47. File-Find-Rule-Imag~ [0.03] (none)
48. File-Find-Rule-MMag~ [0.02] rule to match on mime types
49. File-Find-Rule-MMag~ [0.02] rule to match on mime types
50. File-Find-Rule-MP3I~ [0.01] rule to match on id3 tags, length, bitrate~
51. File-Find-Rule-MP3I~ [0.01] (none)
52. File-Find-Rule-SAUCE [0.02] Rule to match on title, author, etc from a~
53. File-Find-Rule-SAUCE [0.02] Rule to match on title, author, etc from a~
54. File-Find-Rule-Type [0.05] rule to match on mime types
55. File-Find-Rule-Type [0.05] rule to match on mime types
56. File-Find-Rule-Well~ [0.01] Find well-formed XML documents
57. File-Find-Rule-Well~ [0.01] (none)
58. File-Find-Wanted [0.01] More obvious wrapper around File::Find
59. File-Find-Wanted [0.01] More obvious wrapper around File::Find
60. File-Finder [0.01] nice wrapper for File::Find ala find(1)
61. File-Finder [0.01] nice wrapper for File::Find ala find(1)
62. File-Findgrep [0.02] example Locale::Maketext-using application
63. File-Findgrep [0.01] example Locale::Maketext-using application
64. File-Findgrep [0.02] example Locale::Maketext-using application
65. FindBin-Real [1.04] Locate directory of original perl script
66. FindBin-Real [1.02] Locate directory of original perl script
67. FindBin-Real [1.04] Locate directory of original perl script

Cristi Ocolisan
Hi Flash -:)

Usually the File::Find module is already installed with your perl
distribution.

CO

-----Original Message-----
From: FlashMX [mailto:[Email Removed]]
Sent: 10 mai 2005 15:42
To: [Email Removed]
Subject: Re: Setup of ActivePerl Modules HELP!

Hi,

I have a Perl script that requires the following module to be installed.

use File::Find;

open(IN,$File::Find::name) or ...

WHen I ran the PPM and did a search for "Find" I couldn't find the module
"File-Find"? Which one do I have to install?

This is what gets listed:

26. File-Find-Duplicates [0.05] Find duplicate files
27. File-Find-Duplicates [0.05] Find duplicate files
28. File-Find-Iterator [0.3] Iterator interface for search files
29. File-Find-Iterator [0.2] Iterator interface for search files
30. File-Find-Iterator [0.3] Iterator interface for search files
31. File-Find-Rule [0.28] Alternative interface to File::Find
32. File-Find-Rule [0.11] Alternative interface to File::Find
33. File-Find-Rule [0.21] Alternative interface to File::Find
34. File-Find-Rule [0.23] Alternative interface to File::Find
35. File-Find-Rule [0.24] Alternative interface to File::Find
36. File-Find-Rule [0.27] Alternative interface to File::Find
37. File-Find-Rule [0.28] Alternative interface to File::Find
38. File-Find-Rule-Dige~ [0.01] rules for matchig checksum
39. File-Find-Rule-Dige~ [0.01] rules for matchig checksum
40. File-Find-Rule-DIZ [0.05] Rule to match the contents of a
FILE_ID.DIZ
41. File-Find-Rule-DIZ [0.01] Rule to match the contents of a
FILE_ID.DIZ
42. File-Find-Rule-DIZ [0.04] Rule to match the contents of a
FILE_ID.DIZ
43. File-Find-Rule-DIZ [0.05] Rule to match the contents of a
FILE_ID.DIZ
44. File-Find-Rule-File~ [1.21] File::Find::Rule adapted to
Filesys::Virtu~
45. File-Find-Rule-File~ [1.21] File::Find::Rule adapted to
Filesys::Virtu~
46. File-Find-Rule-Imag~ [0.03] rules for matching image dimensions
47. File-Find-Rule-Imag~ [0.03] (none)
48. File-Find-Rule-MMag~ [0.02] rule to match on mime types
49. File-Find-Rule-MMag~ [0.02] rule to match on mime types
50. File-Find-Rule-MP3I~ [0.01] rule to match on id3 tags, length,
bitrate~
51. File-Find-Rule-MP3I~ [0.01] (none)
52. File-Find-Rule-SAUCE [0.02] Rule to match on title, author, etc from
a~
53. File-Find-Rule-SAUCE [0.02] Rule to match on title, author, etc from
a~
54. File-Find-Rule-Type [0.05] rule to match on mime types
55. File-Find-Rule-Type [0.05] rule to match on mime types
56. File-Find-Rule-Well~ [0.01] Find well-formed XML documents
57. File-Find-Rule-Well~ [0.01] (none)
58. File-Find-Wanted [0.01] More obvious wrapper around File::Find
59. File-Find-Wanted [0.01] More obvious wrapper around File::Find
60. File-Finder [0.01] nice wrapper for File::Find ala find(1)
61. File-Finder [0.01] nice wrapper for File::Find ala find(1)
62. File-Findgrep [0.02] example Locale::Maketext-using
application
63. File-Findgrep [0.01] example Locale::Maketext-using
application
64. File-Findgrep [0.02] example Locale::Maketext-using
application
65. FindBin-Real [1.04] Locate directory of original perl script
66. FindBin-Real [1.02] Locate directory of original perl script
67. FindBin-Real [1.04] Locate directory of original perl script







--
To unsubscribe, e-mail: [Email Removed] For additional
commands, e-mail: [Email Removed] <http://learn.perl.org/>
<http://learn.perl.org/first-response>




--
This message was scanned for spam and viruses by BitDefender.
For more information please visit http://linux.bitdefender.com/




--
This message was scanned for spam and viruses by BitDefender.
For more information please visit http://linux.bitdefender.com/

QUOTE

Hi,

I have a Perl script that requires the following module to be installed.

use File::Find;

open(IN,$File::Find::name) or ...


type something like that. btw, it's in the documentation :-)

perl -MFile::Find -e 1; # if it doesn't complain it's installed


--manfred


PHP Help | Linux Help | Web Hosting | Reseller Hosting | SSL Hosting
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Invision Power Board © 2001-2006 Invision Power Services, Inc.