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
David Inglis wrote:
QUOTE

Is there a command to drop an element from an array, or what is the best
way to do this.

Any help appreciated.

It depends. If you want to remove an element based on its contents then use grep:

@array = grep $_ ne 'something', @array;

@array = grep !/something/, @array;


If you want to remove an element and you know its location in the array then use splice:

splice @array, 15, 1; # remove 1 element at 16th position from the beginning

splice @array, -5, 2; # remove 2 elements at 5th and 4th position from the end



John
--
use Perl;
program
fulfillment

David Le Blanc
QUOTE
I always just use this, because I hate removing elements and worrying about
it:

use strict;
use warnings;
sub remove_el (@@) {
my $array = shift;
my @el_rem;
for (sort {$b <=> $a} @_) {
if (! exists $array->[$_]) {
warn 'element ', $_, ' does not exist';
next;
}
push @el_rem, splice(@$array, $_, 1);
}
return @el_rem;
};

my @sample = ('a', 'b', 'c', 'd', 'e', 'f', 'g');
remove_el @sample, 6, 2, 4, 1;

If you just need to remove 1 element a time or a length of elements, you
should just use splice. But sometimes when you have to remove different
elements
in no particular order at no particular time, it gets annoying. Especially if

you are doing something and you have to remove element 3 and 8 at the same
time, and if you remove 3 first, element 8 will be different. We have
subroutines
to make considering this stuff more than once minimal.


I had to stare at that for a while before I realised you were sorting the
splice points in reverse order to ensure that the removal of
one didn't change the indexes of all the others.

Very Nice Code. ™

Now if only I could get the index of an array element without
grepping it!

Rob Dixon
David Inglis wrote:
QUOTE

Is there a command to drop an element from an array, or what is the best
way to do this.

Hi David.

A call to 'splice' is the usual answer, but sometimes you
may want the remaining elements to keep their indices.

A call to 'delete' will shrink an array if you delete from
its end. A delete from the middle of its extent will
leave the size the same but the 'exists' test will then
return false on that element.

Check out this code.

HTH,

Rob


use strict;
use warnings;

my @a = 'a' .. 'j';
printf "Original length: %dnn", scalar @a;

undef $a[2]; # undefine the third element
delete $a[4]; # delete the fifth element
delete $a[9]; # delete the last element
printf "New length: %dnn", scalar @a;

foreach my $i (0 .. 9) {

my $value;

if (not exists $a[$i]) {
$value = 'non-existent'
}
elsif (not defined $a[$i]) {
$value = 'undefined';
}
else {
$value = $a[$i];
}

printf "$a[%d] = %sn", $i, $value;
}

**OUTPUT

Original length: 10

New length: 9

$a[0] = a
$a[1] = b
$a[2] = undefined
$a[3] = d
$a[4] = non-existent
$a[5] = f
$a[6] = g
$a[7] = h
$a[8] = i
$a[9] = non-existent

Wiggins D Anconia
QUOTE
Is there a command to drop an element from an array, or what is the best
way to do this.

Any help appreciated.


perldoc -f delete

http://danconia.org

James Edward Gray II
(Let's keep our discussion on the list, so we can all help and learn.)

On Feb 27, 2004, at 9:28 AM, Cy Kurtz wrote:

QUOTE
Here is my updated code, in case you're interested. It's not as elegant
as your code(I can see I have a lot to learn!), but it works for me.
I'm
still studying your code. Thank you for all your help.

This version is MUCH better, I think. Keep at it! I'll provide some
more general comments below...

QUOTE
#!/usr/bin/perl
#spick.pl
#a program to pick lottery numbers
#select 50 numbers in 10 5 number tickets
#select 10 supernumbers
#all numbers range from 1 to 52
#select each number only once
#select each super number only once
use strict;
use warnings;
my $try;
my @numbers;
my @supers;
my $i;
my $j;

You can eliminate both of the above lines by adding a my into your for
loops as I'll show below.

QUOTE
my $k;
print "nn";
for $i(1..10){

for my $i (1..10) {

QUOTE
for $j(1..5){

for my $j (1..5) {

QUOTE
  $try=int(rand(51)+.5)+1;

Don't do that. rand() returns a number between 0 and what you give as
an argument. Just shave the decimal and add one.

$try = int(rand 51) + 1;

QUOTE
  $k=1;
  while($k<(($i-1)*5+$j)){

Pop quiz time. What's easier to read, the above or this:

while( $k < ( ( $i - 1 ) * 5 + $j ) ) {

We won't bill you for the whitespace. ;)

QUOTE
  if($try != $numbers[$k]){#good number
    $k=$k+1;
  }
  else {#duplicate
    $try=int(rand(51)+.5)+1;
    $k=1;
  }
  }
  $numbers[(($i-1)*5)+$j]=$try;#store number
  if($numbers[($i-1)*5+$j]<10){print "0";}
  print $numbers[(($i-1)*5)+$j],"  ";

This whole section above is "busy work". We try to avoid that in Perl
and just get things done. I know that's not the best explanation, but
it's hard for me to put into words.

Let me try a fresh tactic. I'm going to put another rewrite in here.
But this time, I've tried to mirror how I would do exactly what you are
doing, minus the busy work. ;) I also don't use a module this time,
so it's maybe a little easier to follow. Don't let the length scare
you, it's mostly comments. See if this gives you some fresh
perspective:

#!/usr/bin/perl

use strict;
use warnings;

# a hash cannot have two identical keys, so it makes a handy choice
# for the problem we are trying to solve, even if we are building a
# list that feels more like an array
my(%numbers, %powerballs);

print "nn";
# I'm using identical loops; do note my variable names though as I
# think they tell us a little more about what's really going on
for my $ticket (1..10) {
for my $number (1..5) {
# See how I declare this right where I need it?
# That means I don't have to remember where some variable that
# just shows up again came from. It's self documenting.
# Others will disagree, but it makes the most sense to me.
my $new;
# The next line is where all the magic is. It's a little
# tricky, but it's a common Perl tactic worth learning.
# Let's take it piece by piece. It's just a loop, and what
# it does is almost as basic. It puts random numbers in $new
# until we find one we haven't used before. We check that
# with the hash and that's the tricky part.
# ... while $numbers{$new}++;
# We use $new as a key for the hash, and add one to the
# linked value after we check what that value was.
# The first time we see a value it will be 0 or false,
# ending the loop. Future tests of the number will be higher
# and thus true, causing the loop to try again.
do { $new = int(rand 51) + 1 } while $numbers{$new}++;
printf '%02d ', $new;
} # end block, $number and $new cease to exist here

my $new; # a different $new
do { $new = int(rand 51) + 1 } while $powerballs{$new}++; # same trick
printf "- %02dn", $new;
} # end block, $ticket and $new cease to exist here
print "nn";

__END__

Hope that helps.

Please note that I'm not knocking your code. You have a working
program and that's all you really need. I'm just trying to guide you
towards simplification, to make things easier to read and follow.
It'll also save you time, with future projects.

James

Wiggins D Anconia
QUOTE


perl -lpe '}{*_=*.}{' file

Ooh, an obfuscated verbose way of writing:

perl -lpe'}{$_=$.' file


Huh?  Could someone explain this?  The "}{" makes no sense to me...

- B

You're not the first. There was recently much discussion about this on
the Fun with Perl list, see the threads titled "What does "}{" mean?" at
the following location:

http://www.nntp.perl.org/group/perl.fwp/

http://danconia.org

Charles K. Clarkson
Here's my entry. I took a different approach than James.
I don't like to collect the data and produce the report at the
same time. Both our approaches are valid, though. I tried to
stick with James' report structure.

Perl allows us to be selective with our styles. I find it
a comfortable alternative to many languages that force the
programmer to think in severely limited ways.


#!/usr/bin/perl

use strict;
use warnings;

# List::Util is available on CPAN for 5.6.0 and up
# It comes with 5.8.1 and up.
use List::Util 'shuffle';

# randomize 52 numbers
my @random_numbers = shuffle 1 .. 52;

# randomly choose ten power balls
my @powerballs = ( shuffle 1 .. 52 )[ 0 .. 9 ];

# create an array of arrays to hold the tickets and power balls
my @tickets =
map [
@random_numbers[ $_ * 5 .. $_ * 5 + 4 ],
$powerballs[ $_ ],
],
0 .. 9;

# print report
foreach my $ticket ( @tickets ) {
printf '%02d ' x 5 . "- %02dn", @$ticket;
}

__END__


HTH,

Charles K. Clarkson
--
Head Bottle Washer,
Clarkson Energy Homes, Inc.
Mobile Home Specialists


R. Joseph Newton
Cy Kurtz wrote:

QUOTE
Hi all. I have a little program here that generates a lottery play slip
for the mega-millions game. It selects 50 of the 52 numbers exactly once
over 10 tickets of 5 numbers each. It then selects 10 super ball
numbers, one for each ticket. It then prints it all out(duh).

I wonder if anyone would like to poke fun at my code. I'm kinda new at
this so I'm sure there's a lot done wrong. For starters, the 'use
strict;' and 'use warnings;' lines do not like my code at all(not sure
why)

Then you should find uncomment them and find out why. One thing to bear in
mind--the Perl compiler, and the strict and warnings pragmas used by it, are
only software. They do not have the capacity for anthropomorphic sentiments,
such as liking or disliking.

I know that floods of warnings can be frustrating. What I do when my code
generates such a flood is to use a break [Ctl-C on Windows] to stop execution
right after the warnings start. Then I look at the first error or warning
message. learn what it means, and correct the situation causing it. Then I run
again. I may still have errors and warnings. So again, I look at and deal with
the first one:

while (my $first_message = shift @errors_or_warnings) {
learn_meaning($first_message);
correct_error($first_message);
run_or_compile_script();
}

I am sorry if this doesn't seem helpful. One thing you can do, if you are truly
at a loss trying to understand what is behind an error, is to post the error
message, the code surrounding the line inidcated in the message [with that line
marked], and any declarations or assignment statements affecting variables
involved in the indicated line, to this list. We then will have something solid
on which to base our suggestions.

It looks like James has gone the extra mile for you here, so I would suggest
that you read through his responses, and make sure that you understand the
issues that he is pointing out.

Joseph

David Le Blanc
QUOTE

  $k=1;
  while($k<(($i-1)*5+$j)){

Pop quiz time.  What's easier to read, the above or this:

while( $k < ( ( $i - 1 ) * 5 + $j ) ) {

We won't bill you for the whitespace.  ;)


That is of course assuming that *indiscriminate* padding with
spaces increases readability.

while( $k <(( $i-1 )*5 +$j) ) {

Use the spaces to visibly enhance grouping, and even to provide
visual clues as to the indended (expected?) operator precedence.

If there were even more in that look expression, especially '? :'
expressions, throw in newlines. They're free too!


J u s t m y 2 c w o r t h . : - )

Wiggins D'Anconia
R. Joseph Newton wrote:
QUOTE
Cy Kurtz wrote:


Hi all. I have a little program here that generates a lottery play slip
for the mega-millions game. It selects 50 of the 52 numbers exactly once
over 10 tickets of 5 numbers each. It then selects 10 super ball
numbers, one for each ticket. It then prints it all out(duh).

I wonder if anyone would like to poke fun at my code. I'm kinda new at
this so I'm sure there's a lot done wrong. For starters, the 'use
strict;' and 'use warnings;' lines do not like my code at all(not sure
why)


Then you should find uncomment them and find out why.  One thing to bear in
mind--the Perl compiler, and the strict and warnings pragmas used by it, are
only software.  They do not have the capacity for anthropomorphic sentiments,
such as liking or disliking.

I know that floods of warnings can be frustrating.  What I do when my code
generates such a flood is to use a break [Ctl-C on Windows] to stop execution
right after the warnings start.  Then I look at the  first error or warning
message. learn what it means, and correct the situation causing it.  Then I run
again.  I may still have errors and warnings.  So again, I look at and deal with
the first one:

while (my $first_message = shift @errors_or_warnings) {
learn_meaning($first_message);
correct_error($first_message);
run_or_compile_script();
}

I am sorry if this doesn't seem helpful.  One thing you can do, if you are truly
at a loss trying to understand what is behind an error, is to post the error
message, the code surrounding the line inidcated in the message [with that line
marked], and any declarations or assignment statements affecting variables
involved in the indicated line, to this list.  We then will have something solid
on which to base our suggestions.

It looks like James has gone the extra mile for you here, so I would suggest
that you read through his responses, and make sure that you understand the
issues that he is pointing out.


Good words from Joseph, I will add that until you become familar with
the warnings themselves you may want to consider the 'diagnostics' pragma,

use diagnostics;
perldoc diagnostics

It extends the aptly named 'terse' diagnostic messages.

http://danconia.org

R. Joseph Newton
David Inglis wrote:

QUOTE
Is there a command to drop an element from an array, or what is the best
way to do this.

Any help appreciated.

--
Regards

David Inglis

If at all possible, design around the need.

Joseph

Stuart White
So I figured out from folks on the list, Beginning
Perl, and some print statements that
@list = (2 .. $input);

puts the range of numbers into an array, and that if I
stringified it, then it would put the entire range
into $list[0]

Now that I've figured that bit out, I went on to
remove all the even numbers from the list. I got that
done with this:
foreach (@list)
{
if ($_ % 2 != 0)
{
unshift(@primelist, $_);
@primelistn";
}
}

Now what I'd like to do to test whether or not I have
a prime number is to get at each element in
@primelist, and use the modulus operator on each
element against each element in @list. For example:
$primelist[0] % $list[0]
$primelist[0] % $list[1]
$primelist[0] % $list[2]
$primelist[1] % $list[0]
$primelist[1] % $list[1]
$primelist[1] % $list[2]
$primelist[2] % $list[0]
$primelist[2] % $list[1]
$primelist[2] % $list[2]

and if the result doesn't equal 0 for every test
except for against itself, then I want to unshift it
onto @primelist.

I thought I'd do this with nested foreach loops, but
that didn't seem to work. Any ideas?
Thanks.

__________________________________
Do you Yahoo!?
Get better spam protection with Yahoo! Mail.
http://antispam.yahoo.com/tools

Stuart White
So I figured out from folks on the list, Beginning
Perl, and some print statements that
@list = (2 .. $input);

puts the range of numbers into an array, and that if I
stringified it, then it would put the entire range
into $list[0]

Now that I've figured that bit out, I went on to
remove all the even numbers from the list. I got that
done with this:
foreach (@list)
{
if ($_ % 2 != 0)
{
unshift(@primelist, $_);
@primelistn";
}
}

Now what I'd like to do to test whether or not I have
a prime number is to get at each element in
@primelist, and use the modulus operator on each
element against each element in @list. For example:
$primelist[0] % $list[0]
$primelist[0] % $list[1]
$primelist[0] % $list[2]
$primelist[1] % $list[0]
$primelist[1] % $list[1]
$primelist[1] % $list[2]
$primelist[2] % $list[0]
$primelist[2] % $list[1]
$primelist[2] % $list[2]

and if the result doesn't equal 0 for every test
except for against itself, then I want to unshift it
onto @primelist.

I thought I'd do this with nested foreach loops, but
that didn't seem to work. Any ideas?
Thanks.

oops, here's my code:

#!/usr/bin/perl
# primeNumbers.pl
use warnings;
use strict;
my $input;
my @list;
my @primelist;
print "I want you to enter a list of numbers bigger
than 2.n";
print "To mark the end of your list, enter 0.n";
print "Enter a number that is bigger than 2:t";
$input = <STDIN>;
chomp($input);
print "This is your number: $input n";
@list = (2 .. $input);

print "this is this the fourth element, but has an
index of 3: $list[3]n";
foreach (@list)
{
if ($_ % 2 != 0)
{
unshift(@primelist, $_);
print "this is the inner loop of primelist:
@primelistn";
}
}
print "this is the outer loop of primelist:
@primelistn";


__________________________________
Do you Yahoo!?
Get better spam protection with Yahoo! Mail.
http://antispam.yahoo.com/tools

James Edward Gray II
On Feb 28, 2004, at 11:12 AM, Stuart White wrote:

QUOTE
So I figured out from folks on the list, Beginning
Perl, and some print statements that
@list = (2 .. $input);

Good work.

QUOTE
puts the range of numbers into an array, and that if I
stringified it, then it would put the entire range
into $list[0]

That's not really accurate. What was said to that:

@list = "@list";

Creates a joined string of elements and replaces the list with that one
item. It's perfectly reasonable to stringify an array, without
altering the array's contents:

print "@listn";

QUOTE
Now that I've figured that bit out, I went on to
remove all the even numbers from the list.  I got that
done with this:
foreach (@list)
{
if ($_ % 2 != 0)

That can just be if ($_ % 2), if you prefer. Zero is Perl's idea of
false and it considers anything else true, so it'll work the same.

QUOTE
{
unshift(@primelist, $_);
@primelistn";

The above line is not a valid Perl statement.

QUOTE
}
}

As a shortcut, you can out evens when you make the list, if you
like:

@list = map { $_ % 2 ? $_ : (); } 3..$input;

But that's probably not as pretty.

QUOTE
Now what I'd like to do to test whether or not I have
a prime number is to get at each element in
@primelist, and use the modulus operator on each
element against each element in @list.  For example:
$primelist[0] % $list[0]
$primelist[0] % $list[1]
$primelist[0] % $list[2]
$primelist[1] % $list[0]
$primelist[1] % $list[1]
$primelist[1] % $list[2]
$primelist[2] % $list[0]
$primelist[2] % $list[1]
$primelist[2] % $list[2]

and if the result doesn't equal 0 for every test
except for against itself, then I want to unshift it
onto @primelist.

I thought I'd do this with nested foreach loops, but
that didn't seem to work.  Any ideas?

Define "didn't seem to work"? On second thought, just post that nested
foreach and let us help you fix it.

James

R. Joseph Newton
"R. Joseph Newton" wrote:

QUOTE
David Inglis wrote:

Is there a command to drop an element from an array, or what is the best
way to do this.

Any help appreciated.

--
Regards

David Inglis

If at all possible, design around the need.

Sorry if the above was too curt and cryptic. I do feel, though, that in most
cases the need to delete elements from within an array would raise questions
about whether the array was the appropriate structure for the data. You
certainly have to be aware of the difference between an index-shifting removal
of an element,which will throw offany index-based calculations, and the deletion
of values from elements left in place, which bringsto mind the picture of an
average American strip mall in the Age of Dubya, rows of dismal commercial cells
interspersed with empty storefronts.

In cases where you need to filter a list, Iwould suggest That you structure the
filter processing so that the filtered list is the natural output of the
processing:

my @filtered;
while (my $test_element = shift @$unfiltered) {
push @filtered, $test_element if passes_test($test_element);
}
@$unfiltered = @filtered

Joseph

David Le Blanc
What for you EyeDrop your Email?


-->
--> R. Joseph Newton wrote:
--> > Geez, and I still can't tell whether I'm a "Perl person". I use
Perl as a medium
--> > for programming, which I do in English. I see POD as
documentation for the users of
--> > modules. That is a rather different function than internal
documentation. Tastes
--> > differ, of course. I even found myself softening a bit when an
old friend was
--> > enthusiastically describing contests for the most compact code.
On the whole,
--> > though, I like the idea of writing code in way that make comments
superfluous.
-->
--> Heh :)
-->
--> Programming will likely never be that well documented. Unless your
memeory
--> is the best on the planet you will very likely write code which upon
--> returning to years later say
-->
--> "What the heck was I thinking?"
-->
--> POD and Perl coding can coexist. And should.
-->
--> -Bill-
--> __Sx__________________________________________
--> http://youve-reached-the.endoftheinternet.org/=cut
<http://youve-reached-the.endoftheinternet.org/=cut>


discombobulated....



David le Blanc

--
Senior Technical Specialist <http://www.identity-solutions.com.au/>

I d e n t i t y S o l u t i o n s

Level 1, 369 Camberwell Road, Melbourne, Vic 3124
Ph 03 9813 1388 Fax 03 9813 1688 Mobile 0417 595 550
Email [Email Removed]
<mailto:[Email Removed]>



_____

From: WC -Sx- Jones
[mailto:[Email Removed]]
Sent: Sunday, 29 February 2004 9:16 AM
To: Beginners Perl
Subject: Re: CODING STYLE (are you a Perl Peep?)

R. Joseph Newton
Stuart White wrote:

QUOTE
So I figured out from folks on the list, Beginning
Perl, and some print statements that
@list = (2 .. $input);

puts the range of numbers into an array, and that if I
stringified it, then it would put the entire range
into $list[0]

Now that I've figured that bit out, I went on to
remove all the even numbers from the list.  I got that
done with this:
foreach (@list)
{
if ($_ % 2 != 0)
{
unshift(@primelist, $_);
@primelistn";
}
}

Now what I'd like to do to test whether or not I have
a prime number is to get at each element in
@primelist, and use the modulus operator on each
element against each element in @list.  For example:
$primelist[0] % $list[0]
$primelist[0] % $list[1]
$primelist[0] % $list[2]
$primelist[1] % $list[0]
$primelist[1] % $list[1]
$primelist[1] % $list[2]
$primelist[2] % $list[0]
$primelist[2] % $list[1]
$primelist[2] % $list[2]

and if the result doesn't equal 0 for every test
except for against itself, then I want to unshift it
onto @primelist.

I thought I'd do this with nested foreach loops, but
that didn't seem to work.  Any ideas?
Thanks.

oops, here's my code:

#!/usr/bin/perl
# primeNumbers.pl
use warnings;
use strict;
my $input;
my @list;
my @primelist;
print "I want you to enter a list of numbers bigger
than 2.n";
print "To mark the end of your list, enter 0.n";
print "Enter a number that is bigger than 2:t";
$input = <STDIN>;
chomp($input);
print "This is your number: $input n";
@list = (2 .. $input);

print "this is this the fourth element, but has an
index of 3: $list[3]n";
foreach (@list)
{
if ($_ % 2 != 0)
{
unshift(@primelist, $_);
print "this is the inner loop of primelist:
@primelistn";
}
}
print "this is the outer loop of primelist:
@primelistn";

You must b getting bored and tense with all that code and numbers and stuff.
Take a break, and enjoy some rolling screen graphics:

my @primes = (2);
my $candidate = 3;
while(1) {
my $limit = $candidate ** 0.5;
my $has_factor = 0;
foreach (@primes) {
if ($_ > $limit) {
push @primes, $candidate;
last;
}
unless ($candidate % $_) {
$has_factor = 1;
last;
}
}
unless ($has_factor) {
print "$_ " foreach @primes;
print "n";
}
$candidate++;
}

Joseph

Wc -Sx- Jones
David le Blanc wrote:
QUOTE

What for you EyeDrop your Email?

Just to irritate "the other."
;-)

QUOTE
discombobulated....


why Thx! :)


BTW - Not that I am ignoring anyone but once I finish my latest
WebSphere nightmare I will work on an FTP version of find2perl -- I dont
want the Internet to be lost and unorganized...

more insanity to come...

-Bill-
__Sx__________________________________________
http://youve-reached-the.endoftheinternet.org/

Bob Showalter
Reinhard Mantey wrote:
QUOTE
undef $/;
my $input = <>;
my $pkg_filename  = "longnames.txt";

open(FH, "> $pkg_filename") or die "could not create $pkg_filename";
while ($input =~ m/.../) {

What is your actual regex? At a minimum, you'll need /g modifier. You may
need /m and/or /s as well.

QUOTE
print $1;
FH->print("$1n") or die "could not write to $pkg_filename";
}
FH->close() or die "could not close $pkg_filename";


Bob Showalter
incognito wrote:
QUOTE
Thank you for your attention, Bob.

What is your actual regex? At a minimum, you'll need /g modifier.
You may need /m and/or /s as well.

May be I didn't explained my prob exactly.
I don't have a problem with the regex (and yes, I have the /m /g and
/s). Related to the regex, my script works fine - and I get the
result I want.
I already print the $1 to STDOUT, where it get's redirected to sort
and then to a file.

OK, I thought when you said "no output", that included the STDOUT; thus the
focus on the loop.

QUOTE

My idea was to duplicate the $1 value to another file (write one
value to STDOUT and to a file) and I could not solve it.

It has nothing to do with the $1, as I tried to write a fixed text
and the file didn't gets created.

I notice you don't put an explicit path on the filename. Is it possible the
current directory is something other that what you expect it to be, and the
file is being successfully created in another location?

Incognito
Thank you for your attention, Bob.

QUOTE
What is your actual regex? At a minimum, you'll need /g modifier. You may
need /m and/or /s as well.

May be I didn't explained my prob exactly.
I don't have a problem with the regex (and yes, I have the /m /g and /s).
Related to the regex, my script works fine - and I get the result I want.
I already print the $1 to STDOUT, where it get's redirected to sort and then
to a file.

My idea was to duplicate the $1 value to another file (write one value to
STDOUT and to a file) and I could not solve it.

It has nothing to do with the $1, as I tried to write a fixed text and the
file didn't gets created.

Any idea?

Kind regards

Reinhard

Stuart White
QUOTE
That's not really accurate.  What was said to that:

@list = "@list";

Creates a joined string of elements and replaces the
list with that one
item.  It's perfectly reasonable to stringify an
array, without
altering the array's contents:

print "@listn";


I'm not sure I understand.

QUOTE

That can just be if ($_ % 2), if you prefer.  Zero

That makes perfect sense. Thanks.

QUOTE
{
unshift(@primelist, $_);
@primelistn";

The above line is not a valid Perl statement.


Oh, the "@primelistn"; ? I'm not sure how that got
there...

QUOTE
Now what I'd like to do to test whether or not I
have
a prime number is to get at each element in
@primelist, and use the modulus operator on each
element against each element in @list.  For
example:
$primelist[0] % $list[0]
$primelist[0] % $list[1]
$primelist[0] % $list[2]
$primelist[1] % $list[0]
$primelist[1] % $list[1]
$primelist[1] % $list[2]
$primelist[2] % $list[0]
$primelist[2] % $list[1]
$primelist[2] % $list[2]

and if the result doesn't equal 0 for every test
except for against itself, then I want to unshift
it
onto @primelist.

I thought I'd do this with nested foreach loops,
but
that didn't seem to work.  Any ideas?

Define "didn't seem to work"?  On second thought,
just post that nested
foreach and let us help you fix it.

James


Ok, I went with for loops. As above, I want to get
the modulus of numbers in one array by comparing the
numbers of another array. It's not doing what I
expect it to. I'm not sure if the first loop is
really running either. What am I doing wrong? (Does
that question make sense?)

Also, I'm getting an error: Use of uninitialized value
in modulus (%) at primeNumbers.pl line 40, <STDIN>
line 1.
Illegal modulus zero at primeNumbers.pl line 40,
<STDIN> line 1.
What do those errors mean exactly? Thanks.


__________________________________
Do you Yahoo!?
Get better spam protection with Yahoo! Mail.
http://antispam.yahoo.com/tools

Incognito
Thank you Bob and Owen.

[Bob]
QUOTE
I notice you don't put an explicit path on the filename. Is it possible the
current directory is something other that what you expect it to be, and the
file is being successfully created in another location?

I thought about that and so I tried an absolute path too - no changes.
Also I thought about file / directory permissions and tried the script running
as root - also no changes.

When I create a new script by copy and paste (not writing per hand) with just
the lines related to the file output and change the $1 to something
meaningful - it works.
Therefor I thought, it has to do something with the other script.

First I thought about the "undef $/", but I also added it to the "mini-script"
and it stil worked.


[Owen]
QUOTE
I would have thought that to get a $1 out of that you would have
needed while ($input =~ m/(...)/) ie, brackets around what you wanted
to capture.

Of cause! You're right. The regex is quite big, therefor I ommitted it and
just replaced it by 3 dots. If you like to see the regex, here it is:

----------------- snip ---------------------------------------
my $pat_separator = qr{s*^s+_{10,}s*?$};
my $pat_pkg_name = qr{^(.*?)s+dependenciess*?$};
my $pat_pkg_depend = qr{
(?:^|s*,|s*or|s*and)
[ ]+
([d+]([a-zA-Z][a-zA-Z0-9._ -]*[a-zA-Z0-9]))
(?=(,|s*or|s*and|s*_{10,}|s*Optional|s*Required|s*Recommended))
}x;

while ($input =~ m/$pat_separator
s*?
$pat_pkg_name
/xsmg) {
...
----------------- snap -----------------------------------------


kind regards

Reinhard

Wyndell
Is there any good documentation for in OO PERL Programming?

Stuart White
--- David le Blanc
<[Email Removed]> wrote:
QUOTE

Just for the sake of it, and I apologise profusely
for the top posting..

stuart>Hi David,



QUOTE
Here is a summary of the posted prime calculators
for testing your
results against.

(1) Ohad

stuart>I saw his regexp soln. I was attempting to
stuart>solve it with arrays, loops and maybe hashes.
stuart>I figure that the exercise wouldn't be in the
stuart>book before the regexp chapter if I couldn't do
stuart>it easily (or without TOO much difficulty)
stuart>without them. That's all.

QUOTE
(2) Joseph
stuart>I thought this one was a joke.  Partly because

stuart>of the context it was sent in, partly because
stuart>of what I saw it do. I ran it, and it printed
stuart>out a slew of numbers. It didn't stop after a
stuart>few minutes, so I ended the program.


QUOTE
(3) me (Hey, it's a Mee Too!)

#-------------------------------------------------------
$max=shift||17393;
%notprime=();
@prime=();

for $n (2..$max){
unless($notprime{$n}){
  push @prime,$n;
  $notprime{$_*$n}=1 for 2..$max/$n;
}
}

print "Found $#prime prime numbers..".$/;
print "@primen";

#-------------------------------------------------------

Brief explanation..
(1)
sounds neat.


QUOTE
(2) Joseph posted a calculator which uses the
feature of prime numbers
that the
largest number you need to divide it by is the
square root of itself
($_**0.5)
and that you only need to test if the number you
are examining is
divisible
(ie mod==0) by another prime you have already
found.  Hence, very
quick and
very cpu/memory cheap.  Why not test against
every number?  If you
test against
a non-prime number, you are simply testing
against a multiple of a
prime of
course.

stuart>Ahh, this makes sense, sortof. I'm going to
stuart>need to look at the code again and your
stuart>explanation. This was printing many, many,
stuart>many numbers, some of which sure didn't look
stuart>like they were primes. The sheer number plus
stuart>the proximity of them to each other in
stuart>cardinal? order (2341 2347 2443 etc) (these
stuart>numbers are used to illustrate my probably
stuart>improper use of cardinal, I'm not implying that
stuart>those numbers were outputted by the program)
stuart>made me think that some weren't primes.


QUOTE

(3) A very simple implementation of an erogenous
sieve (iud? did I say
that wrong?)
which keeps all primes in '@primes' and all
'eliminated' entries in
'%notprime'.
quick, but likely more memory intensive than
(2).

This one is a bit confusing.
$max=shift||17393;
stuart>I thought shift was to remove an element from
stuart>the beginning of an array, but it's being used
stuart>in scalar context here. Why? And what is it
stuart>doing?

%notprime=();
QUOTE
@prime=();

for $n (2..$max){
stuart>this makes me think that you were somehow

stuart>assigning a number to $max above. But where
stuart>does 17393 come in? Why not 17394, or 18000?


QUOTE
unless($notprime{$n}){
  push @prime,$n;
  $notprime{$_*$n}=1 for 2..$max/$n;
stuart>I'm not sure I understand this line directly

stuart>above. What I think it says is that it is
stuart>accessing the value within the %notprime hash
stuart>where the key equals the last inputted number
stuart>which I suppose is $n and $_ if $n was pushed
stuart>onto @prime, but just $_ if $n was not pushed
stuart>onto @prime. I don't get the "=1" part
stuart>though. What is that doing? I'm assuming that
stuart>is a for loop there that is working like a
stuart>foreach loop? but I'm not quite sure what it's
stuart>doing.

QUOTE
Cheers.
David



__________________________________
Do you Yahoo!?
Yahoo! Search - Find what youre looking for faster
http://search.yahoo.com

Paul Johnson
David le Blanc said:

QUOTE
Here is a summary of the posted prime calculators for testing your
results against.

And here's a previous thread with few more scripts:

http://groups.google.com/groups?hl=en&lr=&...4.nmc-m.dtag.de

Apologies for the ghastly URL.

You could also search for "dealing with Prime Numbers" in google groups.

--
Paul Johnson - [Email Removed]
http://www.pjcj.net

David Le Blanc
Just for the sake of it, and I apologise profusely for the top posting..

Here is a summary of the posted prime calculators for testing your
results against.

QUOTE
(1) Ohad
#-------------------------------------------------------

perl -e 'print"@{[grep{(1x$_)!~/^(11+?)1+$/}2..shift||1e2]}n"'
<number>
#-------------------------------------------------------
QUOTE
(2) Joseph
#-------------------------------------------------------

my @primes = (2);
my $candidate = 3;
while(1) {
my $limit = $candidate ** 0.5;
my $has_factor = 0;
foreach (@primes) {
if ($_ > $limit) {
push @primes, $candidate;
last;
}
unless ($candidate % $_) {
$has_factor = 1;
last;
}
}
unless ($has_factor) {
print "$_ " foreach @primes;
print "n";
}
$candidate++;
}
#-------------------------------------------------------
QUOTE
(3) me (Hey, it's a Mee Too!)
#-------------------------------------------------------

$max=shift||17393;
%notprime=();
@prime=();

for $n (2..$max){
unless($notprime{$n}){
push @prime,$n;
$notprime{$_*$n}=1 for 2..$max/$n;
}
}

print "Found $#prime prime numbers..".$/;
print "@primen";
#-------------------------------------------------------

Brief explanation..
(1) Ohad posted an obfuscated calculator which runs the array
(2..<number>) through
grep(). The pattern in grep is '(1 x $_) !~ /^(11+?)1+$/' which is
a tricky
way of getting perls enormously powerful regex exgine to determine
if there is
a way of dividing a string of length int($_) characters into a
number of same length
substrings. Probably memory hungry, but definitely cpu hungry for
the regexp.
Note that for any value '$x', "(1 x $x) !~ /^(11=?)1+$/" will
return true if the
number is prime. Excellent way to perform a (quick?) once off test
against a
known number without calculating every other prime. It uses the
obscure perl
@{[ expr ]} to magically interpolate code within quotes.

(2) Joseph posted a calculator which uses the feature of prime numbers
that the
largest number you need to divide it by is the square root of itself
($_**0.5)
and that you only need to test if the number you are examining is
divisible
(ie mod==0) by another prime you have already found. Hence, very
quick and
very cpu/memory cheap. Why not test against every number? If you
test against
a non-prime number, you are simply testing against a multiple of a
prime of
course.

(3) A very simple implementation of an erogenous sieve (iud? did I say
that wrong?)
which keeps all primes in '@primes' and all 'eliminated' entries in
'%notprime'.
quick, but likely more memory intensive than (2).

Cheers.
David


--
Senior Technical Specialist
I d e n t i t y S o l u t i o n s

Level 1, 369 Camberwell Road, Melbourne, Vic 3124
Ph 03 9813 1388 Fax 03 9813 1688 Mobile 0417 595 550
Email [Email Removed]


QUOTE
-----Original Message-----
From: Stuart White [mailto:[Email Removed]]
Sent: Tuesday, 2 March 2004 11:14 AM
To: James Edward Gray II
Cc: [Email Removed]
Subject: Re: listing prime numbers in a range (Beginning Perl
exercise)


That's not really accurate.  What was said to that:

@list = "@list";

Creates a joined string of elements and replaces the
list with that one
item.  It's perfectly reasonable to stringify an
array, without
altering the array's contents:

print "@listn";


I'm not sure I understand.


That can just be if ($_ % 2), if you prefer.  Zero

That makes perfect sense.  Thanks.

{
unshift(@primelist, $_);
@primelistn";

The above line is not a valid Perl statement.


Oh, the "@primelistn";  ?  I'm not sure how that got
there...

Now what I'd like to do to test whether or not I
have
a prime number is to get at each element in
@primelist, and use the modulus operator on each
element against each element in @list.  For
example:
$primelist[0] % $list[0]
$primelist[0] % $list[1]
$primelist[0] % $list[2]
$primelist[1] % $list[0]
$primelist[1] % $list[1]
$primelist[1] % $list[2]
$primelist[2] % $list[0]
$primelist[2] % $list[1]
$primelist[2] % $list[2]

and if the result doesn't equal 0 for every test
except for against itself, then I want to unshift
it
onto @primelist.

I thought I'd do this with nested foreach loops,
but
that didn't seem to work.  Any ideas?

Define "didn't seem to work"?  On second thought,
just post that nested
foreach and let us help you fix it.

James


Ok, I went with for loops.  As above, I want to get
the modulus of numbers in one array by comparing the
numbers of another array.  It's not doing what I
expect it to.  I'm not sure if the first loop is
really running either.  What am I doing wrong?  (Does
that question make sense?)

Also, I'm getting an error: Use of uninitialized value
in modulus (%) at primeNumbers.pl line 40, <STDIN
line 1.
Illegal modulus zero at primeNumbers.pl line 40,
<STDIN> line 1.
What do those errors mean exactly?  Thanks.


__________________________________
Do you Yahoo!?
Get better spam protection with Yahoo! Mail.
http://antispam.yahoo.com/tools

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




David Le Blanc
QUOTE
-----Original Message-----
From: Paul Johnson [mailto:[Email Removed]]
Sent: Wednesday, 3 March 2004 12:13 AM
To: David le Blanc
Cc: [Email Removed]
Subject: RE: listing prime numbers in a range (Beginning Perl
exercise)


David le Blanc said:

Here is a summary of the posted prime calculators for testing your
results against.

And here's a previous thread with few more scripts:

http://groups.google.com/groups?hl=en&lr=&...F-8&oe=UTF-8&th
readm=005101c25d82%2475841fc0%243e861199%40pcf594.nmc-

m.dtag.de&rnum=1&prev=/groups%3Fhl%3Den%26lr%3D%26ie%3DUTF-8%2
6oe%3DUTF-8%26selm%3D005101c25d82%252475841fc0%25243e861199%>
2540pcf594.nmc-m.dtag.de

Great stuff here!

QUOTE

Apologies for the ghastly URL.

For the benefit of those tripped by the ghastly URL provided, here is an
alias provided by tinyurl.com

http://tinyurl.com/23mzl

QUOTE

You could also search for "dealing with Prime Numbers" in
google groups.

--
Paul Johnson - [Email Removed]
http://www.pjcj.net



David Le Blanc
QUOTE
From: Stuart White [mailto:[Email Removed]]
Sent: Tuesday, 2 March 2004 11:55 PM
To: David le Blanc; [Email Removed]
Subject: RE: listing prime numbers in a range (Beginning Perl
exercise)


--- David le Blanc
<[Email Removed]> wrote:

Just for the sake of it, and I apologise profusely
for the top posting..

stuart>Hi David,


Here is a summary of the posted prime calculators
for testing your
results against.

(1) Ohad

stuart>I saw his regexp soln.  I was attempting to
stuart>solve it with arrays, loops and maybe hashes.
stuart>I figure that the exercise wouldn't be in the
stuart>book before the regexp chapter if I couldn't do
stuart>it easily (or without TOO much difficulty)
stuart>without them.  That's all.

(2) Joseph
stuart>I thought this one was a joke.  Partly because
stuart>of the context it was sent in, partly because
stuart>of what I saw it do.  I ran it, and it printed
stuart>out a slew of numbers.  It didn't stop after a
stuart>few minutes, so I ended the program.


You just have to realise that the script is printing the entire
array of primes EVERY time it finds a new one. change the
'while (1)' to 'while( $#primes < 2000 )' to only find 1000
primes, and move the 'print' to after the loop.

QUOTE


(3) me (Hey, it's a Mee Too!)

#-------------------------------------------------------
$max=shift||17393;
%notprime=();
@prime=();

for $n (2..$max){
unless($notprime{$n}){
  push @prime,$n;
  $notprime{$_*$n}=1 for 2..$max/$n;
}
}

print "Found $#prime prime numbers..".$/;
print "@primen";

#-------------------------------------------------------

Brief explanation..
(1)
sounds neat.

(2) Joseph posted a calculator which uses the
feature of prime numbers
that the
largest number you need to divide it by is the
square root of itself
($_**0.5)
and that you only need to test if the number you
are examining is
divisible
(ie mod==0) by another prime you have already
found.  Hence, very
quick and
very cpu/memory cheap.  Why not test against
every number?  If you
test against
a non-prime number, you are simply testing
against a multiple of a
prime of
course.
See above.  It does work afaik.

stuart>Ahh, this makes sense, sortof.  I'm going to
stuart>need to look at the code again and your
stuart>explanation.  This was printing many, many,
stuart>many numbers, some of which sure didn't look
stuart>like they were primes.  The sheer number plus
stuart>the proximity of them to each other in
stuart>cardinal? order (2341  2347 2443 etc) (these
stuart>numbers are used to illustrate my probably
stuart>improper use of cardinal, I'm not implying that
stuart>those numbers were outputted by the program)
stuart>made me think that some weren't primes.



(3) A very simple implementation of an erogenous
sieve (iud? did I say
that wrong?)
which keeps all primes in '@primes' and all
'eliminated' entries in
'%notprime'.
quick, but likely more memory intensive than
(2).

This one is a bit confusing.
$max=shift||17393;

stuart>I thought shift was to remove an element from
stuart>the beginning of an array, but it's being used
stuart>in scalar context here.  Why?  And what is it
stuart>doing?

When 'shift' has no argument, it shifts '@_' which is parameter
arguments in a function, and command line arguments elsewhere.

$max = shift will grab the first command line argument. If
there isn't one, shift == undef, so perl will complete the 'x||y'
expression by evaluating 'y'. If 'shift' returns a number, the 'x||y'
expression is shortcut.

Hence, $max = first argument OR 17393 if there isn't one.

QUOTE

%notprime=();
@prime=();

for $n (2..$max){
stuart>this makes me think that you were somehow
stuart>assigning a number to $max above.  But where
stuart>does 17393 come in?  Why not 17394, or 18000?

17393 is a completely magic number it just so happens where are
exactly 2000 prime numbers between 2 and 17393 inclusive.

QUOTE


unless($notprime{$n}){
  push @prime,$n;
  $notprime{$_*$n}=1 for 2..$max/$n;
stuart>I'm not sure I understand this line directly
stuart>above.  What I think it says is that it is
stuart>accessing the value within the %notprime hash
stuart>where the key equals the last inputted number
stuart>which I suppose is $n and $_ if $n was pushed
stuart>onto @prime, but just $_ if $n was not pushed
stuart>onto @prime.  I don't get the "=1" part
stuart>though.  What is that doing?  I'm assuming that
stuart>is a for loop there that is working like a
stuart>foreach loop?  but I'm not quite sure what it's
stuart>doing.


How about:
for($i= $n*2; $i<$max; $i = $i+$n) {
$notprime{$i} = 1
}

In order to set an entry in the 'notprime' hash for every
multple of '$n' from $n*2 to $max, I iterate from 2 to $max/$n
and set '$notprime{ <current iteration>*$n } = true'.
Hence, when $n is 2,
$notprime{ 2*2 } = 1;
$notprime{ 2*3 } = 1;
$notprime{ 2*4 } = 1;
$notprime{ 2*5 } = 1;
$notprime{ 2*6 } = 1;
.... until $notprime{ 2*($max / 2) } = 1


QUOTE
Cheers.
David



__________________________________
Do you Yahoo!?
Yahoo! Search - Find what you're looking for faster
http://search.yahoo.com


James Edward Gray II
On Mar 1, 2004, at 6:14 PM, Stuart White wrote:

QUOTE

That's not really accurate.  What was said to that:

@list = "@list";

Creates a joined string of elements and replaces the
list with that one
item.  It's perfectly reasonable to stringify an
array, without
altering the array's contents:

print "@listn";


I'm not sure I understand.

Try looking at some sample code:

my @list = qw(Apple Orange Banana);

print "@listn"; # prints Apple Orange Banana; @list is NOT modified.

@list = "@list";
# the above basically means:
# @list = "$list[0] $list[1] $list[2]";
# since there is only one item on the right, it goes it $list[0] and
the other
# indexes are cleared

print "@listn"; # prints Apple Orange Banana, but list only has one
string now

QUOTE
Now what I'd like to do to test whether or not I
have
a prime number is to get at each element in
@primelist, and use the modulus operator on each
element against each element in @list.  For
example:
$primelist[0] % $list[0]
$primelist[0] % $list[1]
$primelist[0] % $list[2]
$primelist[1] % $list[0]
$primelist[1] % $list[1]
$primelist[1] % $list[2]
$primelist[2] % $list[0]
$primelist[2] % $list[1]
$primelist[2] % $list[2]

and if the result doesn't equal 0 for every test
except for against itself, then I want to unshift
it
onto @primelist.

I thought I'd do this with nested foreach loops,
but
that didn't seem to work.  Any ideas?

Define "didn't seem to work"?  On second thought,
just post that nested
foreach and let us help you fix it.

James


Ok, I went with for loops.  As above, I want to get
the modulus of numbers in one array by comparing the
numbers of another array.  It's not doing what I
expect it to.  I'm not sure if the first loop is
really running either.  What am I doing wrong?  (Does
that question make sense?)

It makes perfect sense, yes, but I'm still missing one piece of
information, the broken code you would like fixed. As I said in my
last message, "...just post that nested foreach and let us help you fix
it."

QUOTE
Also, I'm getting an error: Use of uninitialized value
in modulus (%) at primeNumbers.pl line 40, <STDIN
line 1.
Illegal modulus zero at primeNumbers.pl line 40,
<STDIN> line 1.
What do those errors mean exactly?  Thanks.

That's not an error, it's a warning. It means one of the variables
used in the % operation at line 40 doesn't have anything in it. That
test isn't really testing anything and that's probably why your program
isn't running correctly. Perl just thought you would like to know,
since you asked for warnings. Handy, eh?

James

Rob Hanson
I'm not sure, probably by forking and execing. It won't return the result
code from the other program though.


$some_process = 'tcpdump -v -ieth0 >file';

my $pid = fork();
unless ($pid) {
exec($some_process);
die "Can't start $some_process: $!";
}

print "Pid is $pidn";


-----Original Message-----
From: Harry Putnam [mailto:[Email Removed]]
Sent: Tuesday, March 02, 2004 3:34 PM
To: [Email Removed]
Subject: How to capture pid



What is the handy way to record the pid of $some_process in this
fake code?

$some_process = 'tcpdump -v -ieth0 >file')
system("$some_process") or die "Can't start $some_process: $!";

print "Pid is $pidn";

The process is started by a more elaborate perl script at bootup.
and restarted every four hours from syslog. Code above is way simplified.

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

Stuart White
--- James Edward Gray II <[Email Removed]>
wrote:

QUOTE
It makes perfect sense, yes, but I'm still missing
one piece of
information, the broken code you would like fixed.
As I said in my
last message, "...just post that nested foreach and
let us help you fix
it."

My mistake, I thought I had pasted into my message.
Here it is:
===============================
#for loops that will loop through @list and
@primelist, getting the
#modulus of @primelist. I anticipate that this will
isolate prime
#numbers.
for ($i = 0; $i <= $input; $i++)
{
for ($j = 0; $j <= $input; $j++)
{
if ($primelist[$i] % $list[$j])
{
unshift(@newPrimeList, $primelist[$i]);
print "I just added $primelist[$i] to
newPrimeList.n";
}
}
}
print "this is primelist: @primelistn";
print "this is newPrimeList: @newPrimeListn";
================================

__________________________________
Do you Yahoo!?
Yahoo! Search - Find what youre looking for faster
http://search.yahoo.com

In a message dated 3/2/2004 7:57:45 PM Eastern Standard Time,
[Email Removed] writes:
QUOTE
Is there any good documentation for in OO PERL Programming?

Yep. In no particular order:

perldoc perlref
perldoc perlboot
perldoc perltoot
perldoc perltooc
perldoc perlbot
perldoc perlobj
perldoc perlreftut

IMHO, Object Oriented Perl is the best book you can get on the subject.

-will
(the above message is double rot13 encoded for security reasons)

Most Useful Perl Modules
-strict
-warnings
-Devel::DProf
-Benchmark
-B::Deparse
-Data::Dumper
-Clone (a Godsend)
-Perl::Tidy
-Beautifier

Stuart White
QUOTE

Stuart, can we please see the whole script?


#!/usr/bin/perl
# primeNumbers.pl
use warnings;
use strict;
my $input;
my @list;
my @primelist;
my @newPrimeList;
my $i;
my $j;
print "I want you to enter a list of numbers bigger
than 2.n";
print "To mark the end of your list, enter 0.n";
print "Enter a number that is bigger than 2:t";
$input = <STDIN>;
chomp($input);
print "This is your number: $input n";
@list = (2 .. $input);

print "this is this the fourth element, but has an
index of 3: $list[3]n";
#this foreach loop goes through the @list array,
putting the odd
#numbers into a new array, @primelist

foreach (@list)
{
if ($_ % 2 != 0)
{
unshift(@primelist, $_);
print "this is the inner loop of primelist:
@primelistn";
}
}
print "this is the outer loop of primelist:
@primelistn";

#for loops that will loop through @list and
@primelist, getting the
#modulus of @primelist. I anticipate that this will
isolate prime
#numbers.
for ($i = 0; $i <= $input; $i++)
{
for ($j = 0; $j <= $input; $j++)
{
if ($primelist[$i] % $list[$j])
{
unshift(@newPrimeList, $primelist[$i]);
print "I just added $primelist[$i] to
newPrimeList.n";
}
}
}
print "this is primelist: @primelistn";
print "this is newPrimeList: @newPrimeListn";


QUOTE
James



__________________________________
Do you Yahoo!?
Yahoo! Search - Find what youre looking for faster
http://search.yahoo.com

Harry Putnam
"Hanson, Rob" <[Email Removed]> writes:

QUOTE
I'm not sure, probably by forking and execing.  It won't return the result
code from the other program though.


$some_process = 'tcpdump -v -ieth0 >file';

my $pid = fork();
unless ($pid) {
exec($some_process);
die "Can't start $some_process: $!";
}

print "Pid is $pidn";


For some reason the pid printed does not match the output of ps:

actual sample script"
---
#!/usr/local/bin/perl -w

my $cmd = 'tcpdump -v -ttt -i rl0 -w ';
my $fpath = "/var/log/dump";
my $base_fname = "dump_all";
my ($afname);
$afname = "$fpath" . "/" . "$base_fname";

my $pid = fork();
unless ($pid) {
exec("$cmd $afname &");
die "Can't start $cmd: $!";
}

print "Pid is $pidn";
---
Script output:
# dump_all.pl
Pid is 15173
[fwobsd:root] /root
# tcpdump: listening on rl0
ps wwaux|grep tcpdump
root 30335 0.0 1.6 1116 1048 p0 S 6:03PM 0:00.02
tcpdump -v -ttt -i rl0 -w /var/log/dump/dump_all (tcpdump-3.4.0-or)

Note the script outputs 15173 and ps shows 30335

Do you have an idea what is happening here?

James Edward Gray II
On Mar 2, 2004, at 5:38 PM, Stuart White wrote:

QUOTE

--- James Edward Gray II <[Email Removed]
wrote:

It makes perfect sense, yes, but I'm still missing
one piece of
information, the broken code you would like fixed.
As I said in my
last message, "...just post that nested foreach and
let us help you fix
it."

My mistake, I thought I had pasted into my message.
Here it is:

Stuart, can we please see the whole script?

James

Marcos Rebelo
foreach (@files) {
@smallarray = ('$value1',$value2','$value3');
push(@largearray, @smallarray);
}

or

foreach (@files) {
push(@largearray, ['$value1',$value2','$value3']);
}

-----Original Message-----
From: Jim Canfield [mailto:[Email Removed]]
Sent: Tuesday, March 02, 2004 10:40 PM
To: [Email Removed]
Subject: Appending an small array into a larger array in a foreach loop.


Greetings,

I'm having trouble creating an 2 dimensional array that contains the values
of other smaller arrays. For example:

foreach (@files) {

#...Get values
@smallarray = ('$value1',$value2','$value3');

#Append @smallarray to @largearray

??????? Help ME!! ??????

}

The end result would be an array with all the small array values indexed in
a larger array something like this...

(
[ 0, "value1", "value2", "value3" ],
[ 1, "value1", "value2", "value3" ],
[ 2, "value1", "value2", "value3" ],
[ 3, "value1", "value2", "value3" ],
);

Any suggestions? Am I going about this the right way?




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

R. Joseph Newton
Stuart White wrote:


QUOTE
(2) Joseph
stuart>I thought this one was a joke.

Twas. The again it wasn't. Like Uncle Walt I like to cntradict myself. I
actually did mean what I said, both about my impression that you were letting
yourself get caught up in codishness, and that the primary purpose of this
script was to produce rolling screen graphics. Make yourself a cup of tea, sit
back and run it again--without thinking about anything technical. I enjoy the
way theforms move across the sreen as the iterations progress.

It was also designed as open-ended. This is somethng to be aware of anytime you
see a constant value in the control expression of a loop. Unless there is an
internal break [last; in Perl] condition, the procedure is set for continuous
operation.

As an exercise, you might see what adaptations would be required to provide more
sane output, or to set a limiting condition, which brings us to...

QUOTE


This one is a bit confusing.
$max=shift||17393;

Very standard, actually [though I would prefer seeing it with some space around
the asignment and alternative operators.

$max takes the value of shift and the statement returns if their is at least one
argument and the argument evaluates true. If their are no arguments, or the
first argument is 0, the empty string '', or undef, the alternation proceeds to
evaluate the right operator, providing the default value of 17393.
This technique uses the short-circuit evaluation of the || operator. Since the
value is true if either operaor is true, it will return as soon as it finds one
true value, without evaluating the right operator. The converse process can be
used with the && operator. If it finds a single false value, it will return
false without evaluating further. This seems to be used less frequently than
with the ||, though.

Joseph



QUOTE

stuart>I thought shift was to remove an element from
stuart>the beginning of an array, but it's being used
stuart>in scalar context here.  Why?  And what is it
stuart>doing?

%notprime=();
@prime=();

for $n (2..$max){
stuart>this makes me think that you were somehow
stuart>assigning a number to $max above.  But where
stuart>does 17393 come in?  Why not 17394, or 18000?

unless($notprime{$n}){
push @prime,$n;
$notprime{$_*$n}=1 for 2..$max/$n;
stuart>I'm not sure I understand this line directly
stuart>above.  What I think it says is that it is
stuart>accessing the value within the %notprime hash
stuart>where the key equals the last inputted number
stuart>which I suppose is $n and $_ if $n was pushed
stuart>onto @prime, but just $_ if $n was not pushed
stuart>onto @prime.  I don't get the "=1" part
stuart>though.  What is that doing?  I'm assuming that
stuart>is a for loop there that is working like a
stuart>foreach loop?  but I'm not quite sure what it's
stuart>doing.

Cheers.
David



__________________________________
Do you Yahoo!?
Yahoo! Search - Find what youre looking for faster
http://search.yahoo.com

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


Zentara
On Tue, 02 Mar 2004 18:07:58 -0600, [Email Removed] (Harry Putnam)
wrote:
QUOTE

For some reason the pid printed does not match the output of ps:

actual sample script"

Note the script outputs 15173 and ps shows 30335

Do you have an idea what is happening here?

Yeah, you are getting the parent pid in the perl script.
When you try to use system or exec to start another
process, perl gets the pid of the very first part of the whole
transaction, which is usually the pid of the xterm or the
bash shell which will run your command with a second pid.
It usually works ok, because when you kill the parent pid,
it's children get killed too, so we hardly ever have to deal
with them being different.

Use Proc::ProcessTable to get the pid of your program name.
Here is an example:

#!/usr/bin/perl
use warnings;
use strict;
use Proc::ProcessTable;
my $time = time();
my $xtermparentpid;
my $pttydev;

system("xterm -T $time &");
#specify title so you can match for it

my $t = new Proc::ProcessTable;
foreach my $p (@{$t->table}) {
if($p->cmndline =~ /$time/){$xtermparentpid = $p->pid}
}
foreach my $p (@{$t->table}) {
if($p->ppid == $xtermparentpid){$pttydev = $p->ttydev}
}

open(FH,">$pttydev") or warn $!;
for(1..1000){print STDOUT $_,"n"; print FH $_.'a',"n";sleep 1;}

close FH;




--
I'm not really a human, but I play one on earth.
http://zentara.net/japh.html

Jan Eden
incognito wrote:

QUOTE
Thank you for your attention, Bob.

What is your actual regex? At a minimum, you'll need /g modifier.
You may need /m and/or /s as well.

May be I didn't explained my prob exactly. I don't have a problem
with the regex (and yes, I have the /m /g and /s). Related to the
regex, my script works fine - and I get the result I want. I already
print the $1 to STDOUT, where it get's redirected to sort and then
to a file.

My idea was to duplicate the $1 value to another file (write one
value to STDOUT and to a file) and I could not solve it.

It has nothing to do with the $1, as I tried to write a fixed text
and the file didn't gets created.

How about

print FH $1;

Probably too simplistic, but this is the standard way to write to an open filehandle.

- Jan
--
If all else fails read the instructions. - Donald Knuth

James Edward Gray II
On Mar 2, 2004, at 9:10 PM, Stuart White wrote:

QUOTE


Stuart, can we please see the whole script?

Stuart, I reworked the for loops to do what I believe you intended and
made a few other general cleanups. See if this gets you going:

#!/usr/bin/perl
# primeNumbers.pl
use warnings;
use strict;

print "Enter a number that is bigger than 2:t";
chomp( my $input = <STDIN> );
print "This is your number: $input n";
my @list = (2 .. $input);

#this foreach loop goes through the @list array, putting the odd
#numbers into a new array, @primelist
my @primelist;
foreach (@list) { unshift @primelist, $_ if ($_ % 2); }

#for loops that will loop through @list and @primelist, getting the
#modulus of @primelist. I anticipate that this will isolate prime
#numbers.
my @newPrimeList;
PRIMES: for my $possible_prime (@primelist) {
for my $test (3..($possible_prime - 1)) {
next PRIMES unless $possible_prime % $test;
}
push @newPrimeList, $possible_prime;
}
print "this is primelist: @primelistn";
print "this is newPrimeList: @newPrimeListn";

__END__

James

Harry Putnam
zentara <[Email Removed]> writes:

QUOTE
On Tue, 02 Mar 2004 18:07:58 -0600, [Email Removed] (Harry Putnam)
wrote:

For some reason the pid printed does not match the output of ps:

actual sample script"

Note the script outputs 15173 and ps shows 30335

Do you have an idea what is happening here?

Yeah, you are getting the parent pid in the perl script.
When you try to use system or exec to start another
process, perl gets the pid of the very first part of the whole
transaction,  which is usually the pid of the xterm or the
bash shell which will run your command with a second pid.
It usually works ok, because when you kill the parent pid,
it's children get killed too, so we hardly ever have to deal
with them being different.

If you want to log it for SIGHUP in /var/run/process.pid would the
parent work as well?


QUOTE
Use Proc::ProcessTable to get the pid of your program name.
Here is an example:

---8<snip script

Not sure I understand what I'm supposed to be seeing.
None of this output resembles a pid.

I shortened the count up to 10 and watched it output to STDOUT and
to a separate tty... output

STDOUT
1
2
3
[...]

other TTY
1a
2a
3a
[...]'

NOt sure I get what this has to do with two pids involved.

Randal L. Schwartz
QUOTE
"WilliamGunther" == WilliamGunther  <[Email Removed]> writes:

WilliamGunther> IMHO, Object Oriented Perl is the best book you can get on the subject.

And for a tutorial approach ala Learning Perl, check out
Learning Perl Objects References and Modules.

--
Randal L. Schwartz - Stonehenge Consulting Services, Inc. - +
<[Email Removed]> <URL:http://www.stonehenge.com/merlyn/>
Perl/Unix/security consulting, Technical writing, Comedy, etc. etc.
See PerlTraining.Stonehenge.com for onsite and open-enrollment Perl training!

Morbus Iff
QUOTE
WilliamGunther> IMHO, Object Oriented Perl is
the best book you can get on the subject.

RandalLSchwartz> And for a tutorial approach ala Learning
Perl, check out Learning Perl Objects References and Modules.

I'll second both of those suggestions. OOP does have an early
chapter on references, but the ORA book is more in-depth.


--
Morbus Iff ( i put the demon back in codemonkey )
Culture: http://www.disobey.com/ and http://www.gamegrene.com/
Spidering Hacks: http://amazon.com/exec/obidos/ASIN//disobeycom
icq: 2927491 / aim: akaMorbus / yahoo: morbus_iff / jabber.org: morbus

David --- Senior Programmer Anal
R. Joseph Newton wrote:
QUOTE
"Wagner, David --- Senior Programmer Analyst --- WGO" wrote:


I have b
een trying what you suggest, but am not getting the rich text.  Here
is the spot of code:

my $sender = new Mail::Sender {smtp => '....',
from => '[Email Removed]',
to      => $MyTo,
subject => $MySubject};

$sender->MailMsg({  ctype => 'text/rtf',
msg    => $MyEmailData
});

Here is what I get in the email:
{rtf1ansideff0
{fonttbl {f0fmodern Courier New;}
{f1froman Times;}}
deflang1024widowctrlplainfs16noproof
par
par fs16hichaf2dbchaf23lochf2 Run Info:
par fs16hichaf2dbchaf23lochf2 Report used As of Date :
02/28/04 par fs16hichaf2dbchaf23lochf2 Run Date/Time of
Report: 04/03/02-09:43:24

Any ideas what I can do or what I am doing wrong.  I take
the same data and write it to a file and am able to open in Word as
RTF.

Yes.  You are using an inappropriate format for the medium.  E-mail
is basically a plain-text medium.  It has facilities for attching
other files, and there are some extensions for inclusions.  Those
extensions are not portable.

What you see above is good RTF, as far as I can tell.  The
content-type, though, should not say text.  Although the portability
of RTF comes largely from its use of plain text in its control
sequences, it is more an application fromat than text.  Those tags
must be interpreted to display the document properly.
I am just trying to give my user what they asked for and they do not want any attachments. I was using what Jan K suggested, but obviously missing more than just a little bit.


Wags ;)
QUOTE

Why not just attach formatted documents.  It is much less rude.

Also, you should be aware that attempts to mimic the look and feel of
Outlook mail may get you messages tagged as spam or potential
viruses.

Joseph



Any questions and/or problems, please let me know.

Thanks.

Wags ;)
Int: 9-8-002-2224
Ext:



**********************************************************
This message contains information that is confidential
and proprietary to FedEx Freight or its affiliates.
It is intended only for the recipient named and for
the express purpose(s) described therein.
Any other use is prohibited.
****************************************************************

Bob Showalter
Jayakumar Rajagopal wrote:
QUOTE
Hi ,
I have to store list of objects in Array. At the end, @arr contains n
copies of last $obj, but not every $obj created. I tried storing both
object, ref of object. Array contains different references, but same
data. Please help.
thanks,
Jay

the current code looks like this :

$n=0;
my @arr=();
while ( @results )
{
$n++;
my $obj = RowClass->new();
...
...

push @arr, $obj;
}

each call to RowClass::new should be returning a unique bless()'d reference.
If that's the case, the rest of your code looks fine. What is
RowClass::new() doing?

Zentara
On Wed, 03 Mar 2004 10:36:06 -0600, [Email Removed] (Harry Putnam)
wrote:
QUOTE
zentara <[Email Removed]> writes:
On Tue, 02 Mar 2004 18:07:58 -0600, [Email Removed] (Harry Putnam)
wrote:
For some reason the pid printed does not match the output of ps:

actual sample script"

Note the script outputs 15173 and ps shows 30335

Do you have an idea what is happening here?

Yeah, you are getting the parent pid in the perl script.

Use Proc::ProcessTable to get the pid of your program name.
Here is an example:

---8<snip script

Not sure I understand what I'm supposed to be seeing.
None of this output resembles a pid.

NOt sure I get what this has to do with two pids involved.

Well it was just an example to demonstrate that the pid returned
to your perl script is sometimes not the pid of the actual programname
which you are running. I was expecting you to watch top and ps as it
was running, to see the relation between the parent pid and the pid
you are looking for. The command "ps --forest" is a handy way
to get an ascii graphical output to look at.

But here is a more direct example, and in your case, I don't see a
problem. The desired pid is returned on my system.

Back to John Krahn's answer:
Now when you run this code, also have a second shell opened and
in it run "ps --forest". The pid of tcpdump is accurate.
######################################################
#!/usr/bin/perl
$|=1;
open FILE, ">$0.log" or
die "Cannot open file: $!";
my $pid = open DUMP, 'tcpdump -v -ieth0 |' or
die "Cannot open pipe from tcpdump: $!";

print "Pid was $pidn";
print FILE while <DUMP>;
close DUMP or die "Cannot close pipe from tcpdump: $!";
close FILE;
__END__
######################################################

But sometimes this won't work, as when you are calling a perl script,
or doing an "exec". In your original code, you are doing an exec.
Do a "ps --forest" as you run the following, which is using exec:
####################################################
#!/usr/bin/perl
use Proc::ProcessTable;
$|=1;
my $cmd = 'top';

if(fork() == 0){exec( "$cmd >> ppid.log" )}

print "Pid is $pidn";

my $t1 = new Proc::ProcessTable;
my $pid1;
my $commandline = 'top';
foreach my $p (@{$t1->table}){
if($p->cmndline =~ /Q$commandlineE/){
$pid1 = $p->pid; #correct pid to use
print "pid1->$pid1n";
}
}
<>;
__END__
#################################################




If you don't want to mess around with these details, you probably
would like Proc::Background
#####################################################3
#!/usr/bin/perl

use Proc::Background;
my $proc;
my @commands=($cmd1,$cmd2);
foreach my $foo (@commands) {
$proc = Proc::Background->new($foo);
}

###################################################


--
I'm not really a human, but I play one on earth.
http://zentara.net/japh.html

Remko Lodder
perhaps you should let the script do something like SUDO,
and permit it to run a single command, or limited commandset
of root operations, even without password, (you dont want that actually
but since sudo can log stuff, it might be what you aim for)

Cheers

--

Kind regards,

Remko Lodder
Elvandar.org/DSINet.org
www.mostly-harmless.nl Dutch community for helping newcomers on the
hackerscene

-----Oorspronkelijk bericht-----
Van: [Email Removed]
[mailto:[Email Removed]]Namens Silky Manwani
Verzonden: donderdag 4 maart 2004 19:03
Aan: [Email Removed]
Onderwerp: [Perl-beginners] Perl script to switch user to root.


Hello,

I want to write a perl script to switch user (to root). The problem is
that since it asks for the password, I am not sure how I would pass it
thru the script. I know I can run the "su root" with the system command
in perl, but how do I take care of passing the password.

Thanks.


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


_______________________________________________
Perl-beginners mailing list
[Email Removed]
http://lists.elvandar.org/mailman/listinfo/perl-beginners

Silky Manwani
Actually, My program has a list of stuff to be done which needs to be
done as say user "x". Then I need to switch user to root as the rest of
the program needs to do stuff as user root.

so, me doing

system("sudo su root");

doesn't help as it asks for the password.


On Mar 4, 2004, at 10:08 AM, Remko Lodder wrote:

QUOTE
perhaps you should let the script do something like SUDO,
and permit it to run a single command, or limited commandset
of root operations, even without password, (you dont want that actually
but since sudo can log stuff, it might be what you aim for)

Cheers

--

Kind regards,

Remko Lodder
Elvandar.org/DSINet.org
www.mostly-harmless.nl Dutch community for helping newcomers on the
hackerscene

-----Oorspronkelijk bericht-----
Van: [Email Removed]
[mailto:[Email Removed]]Namens Silky Manwani
Verzonden: donderdag 4 maart 2004 19:03
Aan: [Email Removed]
Onderwerp: [Perl-beginners] Perl script to switch user to root.


Hello,

I want to write a perl script to switch user (to root). The problem is
that since it asks for the password, I am not sure how I would pass it
thru the script. I know I can run the "su root" with the system command
in perl, but how do I take care of passing the password.

Thanks.


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


_______________________________________________
Perl-beginners mailing list
[Email Removed]
http://lists.elvandar.org/mailman/listinfo/perl-beginners


Remko Lodder
you obviously didn't read the sudo help pages, you can run the script as
user y
and let it do root things by using
sudo reboot
for example
the system should reboot when you have defined sudo correctly.

man sudo should help you further on the way :)

--

Kind regards,

Remko Lodder
Elvandar.org/DSINet.org
www.mostly-harmless.nl Dutch community for helping newcomers on the
hackerscene

-----Oorspronkelijk bericht-----
Van: Silky Manwani [mailto:[Email Removed]]
Verzonden: donderdag 4 maart 2004 19:15
Aan: Remko Lodder
CC: [Email Removed]
Onderwerp: Re: [Perl-beginners] Perl script to switch user to root.


Actually, My program has a list of stuff to be done which needs to be
done as say user "x". Then I need to switch user to root as the rest of
the program needs to do stuff as user root.

so, me doing

system("sudo su root");

doesn't help as it asks for the password.


On Mar 4, 2004, at 10:08 AM, Remko Lodder wrote:

QUOTE
perhaps you should let the script do something like SUDO,
and permit it to run a single command, or limited commandset
of root operations, even without password, (you dont want that actually
but since sudo can log stuff, it might be what you aim for)

Cheers

--

Kind regards,

Remko Lodder
Elvandar.org/DSINet.org
www.mostly-harmless.nl Dutch community for helping newcomers on the
hackerscene

-----Oorspronkelijk bericht-----
Van: [Email Removed]
[mailto:[Email Removed]]Namens Silky Manwani
Verzonden: donderdag 4 maart 2004 19:03
Aan: [Email Removed]
Onderwerp: [Perl-beginners] Perl script to switch user to root.


Hello,

I want to write a perl script to switch user (to root). The problem is
that since it asks for the password, I am not sure how I would pass it
thru the script. I know I can run the "su root" with the system command
in perl, but how do I take care of passing the password.

Thanks.


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


_______________________________________________
Perl-beginners mailing list
[Email Removed]
http://lists.elvandar.org/mailman/listinfo/perl-beginners



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.