Re: pattern matching question

2004-12-23 Thread Chris Charley
- Original Message - 
From: "John McCormick"


i'm trying to figure out how to split a file delimited
by commas and newlines.
@data = split (/\n|\,/, )
the only problem is that some of the data fields are
strings enclosed in double quotes, and within some of
those double quotes are more commas.  that's too
tricky for me.  how do i do that?
thanks!
court
Hi John
There is a module that comes bundled with Perl, Text::ParseWords. A sample 
program below that you can copy and run. (Include the __DATA__ line and the 
2 lines that follow).

#!/usr/bin/perl
use strict;
use warnings;
use Text::ParseWords;
my @data;
while() {
chomp;
push @data, parse_line ",", 0, $_;
}
print join "\n", @data;
__DATA__
one,word,"couple words, with comma","another word"
"string, with, commas",parse_words
parse_line, one of the available functions, takes 3 arguments: the delimiter 
(the comma), a flag, and the line to parse.

You may want to read up by running the line below at your command prompt:
perldoc Text::ParseWords
Season's best
Chris 


--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 



Re: complex data structure

2005-01-10 Thread Chris Charley
I hope someone can explain this related question. When I run the code below 
on Brano's data structure, 'each' gives me false results but 'keys' gives me 
correct results. I'm kind of stumped!

#!/usr/bin/perl
use strict;
use warnings;
my $hash = {
 'test1' => [
  {
'test1_a' => 'a',
'test1_b' => 'b'
  },
  {
'test1_a' => 'a',
'test1_b' => 'b'
  },
  {
'test1_c' => 'c'
  },
  {
'test1_d' => 'd'
  }
]
   };
for my $anon (@{$hash->{test1}}) {
  for (my ($k, $v) = each %$anon) {
 print "$k: $v\n";
  }
  print "### EACH ###\n";
}
print "\n\n";
for my $anon (@{$hash->{test1}}) {
  for (keys %$anon) {
 print "$_: $anon->{$_}\n";
  }
  print "### KEYS ###\n";
}
__END__
(This is what prints out)
C:\perlp>perl t1.pl# my command line
test1_a: a
test1_a: a
### EACH ###
test1_a: a
test1_a: a
### EACH ###
test1_c: c
test1_c: c
### EACH ###
test1_d: d
test1_d: d
### EACH ###
test1_a: a
test1_b: b
### KEYS ###
test1_a: a
test1_b: b
### KEYS ###
test1_c: c
### KEYS ###
test1_d: d
### KEYS ###
C:\perlp> 


--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 



Re: complex data structure

2005-01-10 Thread Chris Charley
- Original Message - 
From: <[EMAIL PROTECTED]>
Newsgroups: perl.beginners
To: "Chris Charley" <[EMAIL PROTECTED]>
Cc: 
Sent: Monday, January 10, 2005 1:23 PM
Subject: Re: complex data structure



- Original Message -----
From: Chris Charley <[EMAIL PROTECTED]>
Date: Monday, January 10, 2005 12:59 pm
Subject: Re: complex data structure
I hope someone can explain this related question. When I run the
code below
I can try, I personaly perfer RoHoH..., looks like you have RoHoAoH
on Brano's data structure, 'each' gives me false results
Does it ?? Remember each will not itterate on Data sets. It simply returns 
key and value.
Right
but 'keys' gives me correct results. I'm kind of stumped!
because 'keys' itterates over data structures.
OK

test1[0] is a referance to a 2 key hash, since you called 'each' only 
once, you only got to see first part of the data set :). Here is some code 
to explain it, let me know if you need more help.

Thank you for your reply with the explaination. I now understand that 'each' 
will not iterate where keys does. Anyway, I will have to mull it over  :-)

I changed the for loop to a while loop and 'each' worked the way I was 
expecting with the for loop. I was trying to do the assignment in the for 
loop and that was incorrect.

Changed that line
for (my ($k, $v) = each %$anon)
TO
while (my ($k, $v) = each %$anon)
Chris

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



Re: Variable-sized hash of booleans

2005-02-04 Thread Chris Charley
You can use grep.
my %hash = (ONE => 1, TWO => 0, THREE => 1);
if (grep {! $hash{$_}} keys %hash) {
print "false\n";
}
else {
print "true\n";
}
Prints 'false'.
Chris 


--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 



Re: Variable-sized hash of booleans

2005-02-04 Thread Chris Charley
You can use grep.
my %hash = (ONE => 1, TWO => 0, THREE => 1);
if (grep {! $hash{$_}} keys %hash) {
print "false\n";
}
else {
print "true\n";
}
Prints 'false'.
Guess it would be helpful to explain how grep works here. From the perlfunc 
man page:
Evaluates the BLOCK or EXPR for each element of LIST (locally setting $_ to 
each element) and returns the list value consisting of those elements for 
which the expression evaluated to true. In scalar context, returns the 
number of times the expression was true.

In the code above, ! $hash{$_} evals to true when $hash{TWO} is evaluated, 
so grep, being in scalar context, would return 1, the number of elements in 
%hash which evaluated to 'true '.If all values were 'true', (1's), then grep 
would return 0 since !$hash{$_} would be false for every element in that 
case.

Chris

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 



Re: Question on sorting file

2005-02-14 Thread Chris Charley
Hello Vishal,
File::Sort does external sorting for large files.
http://search.cpan.org/~cnandor/File-Sort-1.01/Sort.pm
Chris
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 



Re: date math

2004-03-29 Thread Chris Charley

"Andrew Gaffney" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> R. Joseph Newton wrote:
> > Andrew Gaffney wrote:

[snip]

> I didn't do it this way because there is a "first" pay period. If there
are only 2 pay
> periods from the starting date, you can't build a list of 6. My way takes
that into
> account. Below is the modified code based on (most of) your suggestions.
>
> use constant PAY_PERIOD_DAYS => 14;
> my @pay_periods;
> my @final_pay_periods;
> my $last_period_end = Date::Simple->new('2004-03-20');


> my @lt = localtime;
> my $today = Date::Simple->new($lt[5]+1900, $lt[4]+1, $lt[3]);

Here you could just say:

my $today = Date::Simple->new;


> while($today > $last_period_end + 1) {
>my $new_start = $last_period_end + 1;
>my $new_end = $last_period_end + PAY_PERIOD_DAYS;
>push @pay_periods, "$new_start to $new_end";

You can make the list ordered from most recent period to least recent
by saying:

unshift @pay_periods, "$new_start to $new_end";


>$last_period_end = $new_end;
> }


> my $period_counter = 0;
> foreach(reverse @pay_periods) {
>$period_counter++;
>last if($period_counter > 6);
>push @final_pay_periods, $_;
> }

Not necessary to do the above, but need this statement to
limit @pay_periods to most recent 6 periods (if there are 6)

splice @pay_periods, 6 if @pay_periods > 6;


HTH,
Chris



-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: Spliting some path

2004-04-13 Thread Chris Charley

- Original Message - 
From: <[EMAIL PROTECTED]>
Newsgroups: perl.beginners
To: <[EMAIL PROTECTED]>
Sent: Saturday, April 10, 2004 12:56 PM
Subject: Spliting some path


> How can I split some path to directories
> for example if my $path is "/home/ftp/some/file"
> how can I get elements /home, than ftp, than some, and for last - file
> I mean without split function, is there any other smarter way for doing
> it. because if I have /home/ftp/some\/other dir/file
> if I split it with "/" it won't return true directories.
> 
> thanks

Hi

This program will do what you want, capturing all desired directories.


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

my $path = "/home/ftp/some/file";
my $count = $path =~ tr/\///;

my @dirs;
for my $cnt (1..$count) {
 my ($dir) = $path =~ m|^( (?:/[^/]+){$cnt} )|x;
 push @dirs, $dir;
}

print join "\n", @dirs;


HTH
Chris


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: Date calculation

2004-04-21 Thread Chris Charley

- Original Message - 
From: "Jan Eden" <[EMAIL PROTECTED]>
Newsgroups: perl.beginners
To: "Perl Lists" <[EMAIL PROTECTED]>
Sent: Wednesday, April 21, 2004 1:29 PM
Subject: Date calculation


Hi,

I need to find the number of days between two dates. The Perl Cookbook
provides this solution:

use Date::Calc qw(Delta_Days);
@bree = (1981, 6, 16);  # 16 Jun 1981
@nat  = (1973, 1, 18);  # 18 Jan 1973
$difference = Delta_Days(@nat, @bree);

But there's a hook: I need to calculate a room price based on the number of
days, where a day costs $80 during summer (July 1 through September 15) and
$55 otherwise (September 16 through June 30).

Since people can book a room for any interval, I somehow have to integrate
the dividing day and month values


Hello Jan
Maybe something like this would do what you want   :-)

#!/usr/bin/perl
use strict;
use warnings;
use Date::Calc qw/Delta_Days Date_to_Days Add_Delta_Days/;

my $beg = Date_to_Days(2004, 7, 1);
my $end = Date_to_Days(2004, 9, 15);

my @chk_in = (2004, 6, 28);
my @chk_out = (2004, 7, 5);

my $j = Delta_Days(@chk_in,@chk_out);

for ( my $i = 0; $i <= $j; $i++ ){
 my @date = Add_Delta_Days(@chk_in,$i);
 printf("%4d-%02d-%02d\t", @date);
 my $day = Date_to_Days(@date);
 print $day >= $beg && $day <= $end ? "\$80.00\n" : "\$55.00\n";
}

I took this example from Dtae::Calc man pages
- perldoc Date::Calc

The output was
2004-06-28  $55.00
2004-06-29  $55.00
2004-06-30  $55.00
2004-07-01  $80.00
2004-07-02  $80.00
2004-07-03  $80.00
2004-07-04  $80.00
2004-07-05  $80.00


HTH,
Chris




-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: Date calculation

2004-04-21 Thread Chris Charley

- Original Message - 
From: "Chris Charley" <[EMAIL PROTECTED]>
Newsgroups: perl.beginners
To: <[EMAIL PROTECTED]>
Sent: Wednesday, April 21, 2004 6:48 PM
Subject: Re: Date calculation


> 
> - Original Message - 
> From: "Jan Eden" <[EMAIL PROTECTED]>
> Newsgroups: perl.beginners
> To: "Perl Lists" <[EMAIL PROTECTED]>
> Sent: Wednesday, April 21, 2004 1:29 PM
> Subject: Date calculation
> 
> 
> Hi,
> 
> I need to find the number of days between two dates. The Perl Cookbook
> provides this solution:


> Hello Jan
> Maybe something like this would do what you want   :-)


> for ( my $i = 0; $i <= $j; $i++ ){
This for loop should be: for ( my $i = 0; $i < $j; $i++ )
so that $i never equals $j (checkout day).

>  my @date = Add_Delta_Days(@chk_in,$i);
>  printf("%4d-%02d-%02d\t", @date);
>  my $day = Date_to_Days(@date);
>  print $day >= $beg && $day <= $end ? "\$80.00\n" : "\$55.00\n";
> }



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




Re: Date calculation

2004-04-23 Thread Chris Charley

- Original Message - 
From: "Jan Eden" <[EMAIL PROTECTED]>
Newsgroups: perl.beginners
To: "Chris Charley" <[EMAIL PROTECTED]>; "Perl Lists"
<[EMAIL PROTECTED]>
Sent: Thursday, April 22, 2004 3:56 AM
Subject: Re: Date calculation


Hi Chris,

Thanks! That's exactly what I needed. Works perfectly - and if you need an
apartment for rent at the Lago di Garda (Italy)... ;-)

- Jan

Glad my suggestion worked for you Jan. Yes - my last time to Europe was on a
motorcycle tour but didn't make it to Italy!
Chris



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




Re: Finding missing numbers in sequence

2004-05-13 Thread Chris Charley

- Original Message - 
From: "Larry Wissink" <[EMAIL PROTECTED]>
Newsgroups: perl.beginners
To: <[EMAIL PROTECTED]>
Sent: Wednesday, May 12, 2004 6:39 PM
Subject: Finding missing numbers in sequence


I have a problem that I thought would be perfect for Perl, except that I
seem to be using all my system resources to run it.  Of course this
probably means I'm doing it the wrong way...



The problem:

We have a backup server that is missing records from the production
server for a particular table.  We know that it should have sequential
records and that it is missing some records.  We want to get a sense of
the number of records missing.  So, we know the problem started around
the beginning of March at id 70,000,000 (rounded for convenience).
Currently we are at 79,000,000.  So, I dumped to a file all the ids
between 70,000,000 and 79,000,000 (commas inserted here for
readability).  I need to figure out what numbers are missing.  The way
that seemed easiest to me was to create two arrays.  One with every
number between 70 and 79 million, the other with every number in our
dump file.  Then compare them as illustrated in the Perl Cookbook using
a hash.


So, does anybody have a suggestion for a better way to do it in Perl?

 Hello Larry,

I was able to come up with a simple script that doesn't require using an
array/hash, so that your mem problems should not occur.

NOTE: the beginning number has to have 1 subtracted from it. This is a first
case situation so that that the algorithm works for the set. Also, if there
are missing records after the last number read in, it won't find that
sequence, but that should be easy enough to find (in this example, any
numbers after 20).

HTH
Chris


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

my @missing;

my $i = 0; # Or 70,000,000 - 1 (69,999,999)

while() {
 if ($_ != ++$i) {
  push @missing, $i .. $_ - 1;
  $i = $_;
 }
}

print join "\n", @missing;

__DATA__
4
5
7
10
12
13
14
15
20


OUTPUT
1
2
3
6
8
9
11
16
17
18
19



-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: Find closest value

2004-05-16 Thread Chris Charley

- Original Message - 
From: "Mike Blezien" <[EMAIL PROTECTED]>
Newsgroups: perl.beginners
To: "Perl List" <[EMAIL PROTECTED]>
Sent: Sunday, May 16, 2004 12:50 PM
Subject: Find closest value


> Hello,
>
> is it possible, with perl, to find the closest numerical value to a set
value.
> IE. a set value of 15 and I have five values, 208,258,56,123
>
> is there a function too go through the five values array to find the
closest to
> 15 ??

Hi Mike
Doing a quick search on CPAN didn't turn up anything, (as far as I can
tell),
but the following code will do what you want, I believe, but is not a
function.

Chris

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

my $set = 15;
my @vals = (208,258,56,123);

my ($min_idx) = map{$_->[0]}
  sort{ $a->[1] <=> $b->[1]}
  map{[$_, abs($vals[$_]-$set)]} 0..$#vals;

print "index of element closest to $set is $min_idx",
   " with value $vals[$min_idx]\n";

__END__
*** Output ***
index of element closest to 15 is 2 with value 56



-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: Finding a string in a file

2004-05-25 Thread Chris Charley

- Original Message - 
From: "Debbie Cooper" <[EMAIL PROTECTED]>
Newsgroups: perl.beginners
To: <[EMAIL PROTECTED]>
Sent: Tuesday, May 25, 2004 12:11 PM
Subject: Finding a string in a file


> I need to search for the occurrence of a string in a file that is buried
in
> directories.  So, for example, I have a directory structure that looks
like
> this C:\data\elec\1\220\webdata.tab.  The last three folders change
> frequently so I can have c:\data\appl\3\180\webdata.tab and so on.  The
file
> I'm searching will always be called webdata.tab.  It is a tab delimited
file
> with headers and I need to search the header for a specific word like
> "Brand" and somehow return the directory structure where the word is
found.
> Can this be done in "beginning" perl?
>
> Thanks,
> Debbie
>

Hi Debbie

The following code will do what you want, I think.

#!/usr/bin/perl
use strict;
use warnings;
use File::Find;

my @directories = ("C:/data/");

find(\&wanted,  @directories);

sub wanted {
if ($_ eq "webdata.tab") {
open my $fh, "<", "$_" or die "open $_: $!";
while (my $line = <$fh>) {
if ($line =~ /\bBrand\b/) {
print"$File::Find::dir\n";
last;
}
}
close $fh;
}
}


HTH
Chris



-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: Array help almost correct

2004-05-26 Thread Chris Charley
[snip]

> my $acceptable = qr/^(?:sp|lp|ep12|ffp|vid|dvd|bx|bkk|cd|csd)$/;
> 
> and then using $acceptable to do the matchings, such as
> 
> grep /$acceptable/, @array
> 
> 
> it would be faster and more readable :-)

If the acceptable list is that large, using a hash would be TMTOWTDI  :-)

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

my %acceptable = map {$_ => 1} qw/ sp lp ep12 ffp vid dvd bx bkk cd csd /;

my @a = ([qw/ cd csd cd /], [qw/ abc ed csd cd /]);

for (@a) {
 if (grep {not $acceptable{$_}} @$_) {
  print "Not acceptable\n";
 }
 else {
  print "OK\n";
 }
}

Chris


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: printing contents between lines

2004-06-03 Thread Chris Charley

- Original Message - 
From: "Sidharth" <[EMAIL PROTECTED]>
Newsgroups: perl.beginners
To: <[EMAIL PROTECTED]>
Sent: Thursday, June 03, 2004 3:44 PM
Subject: printing contents between lines


hi all ,
 consider the contentes of file as below

[snip file contents]

how  to  print  all the line between  tools:   and  # Not a target:   only

Hello Sidharth,

The following code will do it  :-)

while(<>) {
 if (my $line = /tools:/ .. /# Not a target:/) {
  print unless $line =~ /E/;
 }
}

Note: $line will contain number of lines inclusive from 'tools:' until '#
Not a target:'. The last line, in addition to the count will have an 'E0'.
That is, if there are 6 lines, $line would have '6E0' on the last line.

Chris



-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: printing contents between lines

2004-06-03 Thread Chris Charley

- Original Message - 
From: "Chris Charley" <[EMAIL PROTECTED]>
Newsgroups: perl.beginners
To: <[EMAIL PROTECTED]>
Sent: Thursday, June 03, 2004 7:09 PM
Subject: Re: printing contents between lines


>
> - Original Message - 
> From: "Sidharth" <[EMAIL PROTECTED]>
> Newsgroups: perl.beginners
> To: <[EMAIL PROTECTED]>
> Sent: Thursday, June 03, 2004 3:44 PM
> Subject: printing contents between lines
>
>
> hi all ,
>  consider the contentes of file as below
>
> [snip file contents]
>
> how  to  print  all the line between  tools:   and  # Not a target:   only
>
> Hello Sidharth,
>
> The following code will do it  :-)
>
> while(<>) {
>  if (my $line = /tools:/ .. /# Not a target:/) {
>   print unless $line =~ /E/;
>  }
> }
>
> Note: $line will contain number of lines inclusive from 'tools:' until '#
> Not a target:'. The last line, in addition to the count will have an 'E0'.
> That is, if there are 6 lines, $line would have '6E0' on the last line.
>
> Chris

I see that you didn't want 'tools:' printed by your specifications.
Change line above to:

print unless $line == 1 || $line =~ /E/;



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




Re: reading commandline parameters and <>

2004-06-07 Thread Chris Charley
> I am sorry I did not give the real situation before, I want to execute
> this on command line like
> 
> perl -pe 's/$ARGV[1]/$ARGV[2]/' filename OLDSTR NEWSTR
> 
> Is this possible ? 
> 
> Thanks
> Ram


Why not

perl -pe 's/OLDSTR/NEWSTR/' filename



-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: reading commandline parameters and <>

2004-06-07 Thread Chris Charley

- Original Message - 
From: "Chris Charley" <[EMAIL PROTECTED]>
Newsgroups: perl.beginners
To: <[EMAIL PROTECTED]>
Sent: Monday, June 07, 2004 2:07 PM
Subject: Re: reading commandline parameters and <>


> > I am sorry I did not give the real situation before, I want to execute
> > this on command line like
> > 
> > perl -pe 's/$ARGV[1]/$ARGV[2]/' filename OLDSTR NEWSTR
> > 
> > Is this possible ? 
> > 
> > Thanks
> > Ram
> 
> 
> Why not
> 
> perl -pe 's/OLDSTR/NEWSTR/' filename

Sorry, To do it your way:

perl -pe 'BEGIN{$y=pop;$x=pop} s/$x/$y/' filename OLDSTR NEWSTR



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




Re: Date and time calculation

2004-06-17 Thread Chris Charley
> Hi there,
>
> I've got a date field and a time field, how can I effectively subtract the
> field ($date $time) - ($date2 $time2) from each other. I am using these
> two fields to determine a server's uptime according to my database in
> days,hours,minutes,seconds.
> Kind Regards,
> Werner Otto

Perhaps this is want you are looking for   :-)

#!/usr/bin/perl
use strict;
use warnings;
use Date::Calc qw / Delta_DHMS /;

my $date1 = "2004-02-20 12:10:30";
my $date2 = "2004-10-30 12:40:22";

print join " ", Delta_DHMS(split /[-\s:]/, "$date1 $date2");

*** Output
253 0 29 52

Chris



-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: regex in perl.

2004-06-17 Thread Chris Charley
http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&selm=slrnbnjntp.7er.xx087%40smeagol.ncf.ca

The link above shows an array of patterns being used.

http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&q=%22array+of+patterns%22+group%3Acomp.lang.perl.misc&meta=group%3Dcomp.lang.perl.misc

The link above is a search result on arrays of patterns - should be a good
start to help you understand.

HTH
Chris



-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: regex in perl.

2004-06-18 Thread Chris Charley

- Original Message - 
From: "Rod Za" <[EMAIL PROTECTED]>
Newsgroups: perl.beginners
To: <[EMAIL PROTECTED]>
Sent: Thursday, June 17, 2004 6:15 PM
Subject: regex in perl.


> Hello,
>
> Someone know how can i search this in a file using regex?

Hello Rod,
My head must've been in the clouds  :-(

This code will do what you want.

while () {
 if (/%!/ || /\004%!/ || /\033%-12345X%!PS/ ||
/LANGUAGE\s?=\s?POSTSCRIPT/i) {
  print;
 }
}

__DATA__
%!s
yyy question \033%-12345X%!PSttt
---

LANGUAGE=POSTSCRIPT
LANGUAGE = postscript

Chris




-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: puzzled

2004-06-19 Thread Chris Charley

- Original Message - 
From: "Pedro Antonio Reche" <[EMAIL PROTECTED]>
Newsgroups: perl.beginners
To: <[EMAIL PROTECTED]>
Sent: Friday, June 18, 2004 9:43 AM
Subject: puzzled


> Hi there, I am puzzled by the 'build_seq' subroutine in following code.
> #!/usr/sbin/perl -w
> use strict;
> use vars qw($USAGE);
>
> # random sequence generator #
> # -c=1 option will cause prot sequences to be built
> # using vertebrate aa frequencies,
> # with option -a putting a 1st methionine residues on. Frequencies are
> # calculated from the NCBI human RefSeq protein sequences
> # -c and -a only affect protein sequences
> # -a only works in conjunction with -c
> # -n number of random sequences, default = 1
>
> use Getopt::Long;
> my ($length,$type,$filename,$comp,$met);
>
> $USAGE = 'usage: generate_random_seq.pl --length=1000 --type=dna
> --filename=/tmp/test.seq --number=50';
>
> my %alphabets = ( 'dna' => [qw(C A G T)],
>   'rna' => [qw(C A G U)],
>   'prot'=> [qw( A C D E F G H I K L M N P Q R S T V W Y)],
>   );
> # make random num from 1-1. numbers in this array reflect the
frequency,
> # e.g., a random number from 1.744 = A, 745-991 = C etc;
> my @aa_frequencies = qw(744 991 1398 2017 2378 3104 3349 3726 4239 5273
> 5443
> 5749 6410 6848 7455 8263 8760 9340 9488 9713
1);
> my $number = 1;
>
> &GetOptions
>   (
>'l|length:s'  => \$length,
>'t|type|m|alphabet:s' => \$type,
>   );
>
> assert ( $type && defined ($alphabets{lc $type}),
>  $USAGE);
> assert ( $length && $length =~ /^\d+$/, $USAGE );
>
> foreach my $num (1..$number) {
>my $sequence = "";
>my $alphabet = $alphabets{lc $type};
>my $sspace = scalar @$alphabet;
>if (!$comp || $type ne 'prot') {

As far as I can tell, $comp is never assigned a value, so !$comp is true and
this branch of the if statement is executed even when type is 'prot'. The
branch below, 'build_seq($length, [EMAIL PROTECTED])', is never reached when
type = prot (because $comp is undefined).


>   foreach ( 1..$length ) {
>  $sequence .= $alphabet->[ int rand($sspace) ];
>   }
>}elsif ($type eq 'prot') {
>   ($sequence) = build_seq($length, [EMAIL PROTECTED]);
> print "yes $sequence\n\n\n";
>}
> print "$sequence\n";
> }
> sub assert { die $_[1] unless( $_[0] ); }
> sub build_seq {
>#takes seqlen and ref to frequency data as parameters
>my ($len, $pf)  = @_;
>my $str;
>my  $i;
>$i = 2; #1
>for ($i .. $len-1) {
>   print "$i\n";
>   my $aa = int(rand (1)) ;
>   my $j = 0;
>   while ($pf->[$j] < $aa && $j <19) {
>  $j++;
>   }
>   $str .= $alphabets{'prot'}[$j];
>}
>print "str is $str\n"; #2
>#return $str; # 3
> }
> I run the program as
> ./program.pl --type prot --length 9
> and the program spit out a random string of 9 characters such as
> KWNNNPITS
>
> However, the string should be of 7 characters ($i = 2 in # 1), print
> does not work within the subroutine (#2). and subroutine is returning a
> value despite return is commented out (#3). Does anyone understand why
> this is working this way?
> Thanks in advance for any insight.
> Cheers
>

Hope this fixes your problem,
Chris



-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: Re:seach a number in a file

2004-06-19 Thread Chris Charley

- Original Message - 
From: "Jorge Goncalves" <[EMAIL PROTECTED]>
Newsgroups: perl.beginners
To: <[EMAIL PROTECTED]>
Sent: Friday, June 18, 2004 4:35 AM
Subject: Re:seach a number in a file


> Hi, I have a text file like this:

[snip file contents, they're posted below]

> How can i do in Perl to get the first number if the last part of the
> line doesn't contains extractStat.
> for exemple here to get only the number 7.
>
> Thanks

Hello Jorge,
This code will do what you want. You may also want to check:

For the 'm' modifier
perldoc perlretut (see using character classes)
perldoc perlre

Could not find docs for the 'g' modifier. Maybe someone else could point
out where it is best explained.

Chris

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

{
 local $/;# undefine input record separator - read in whole file as
1 line ($file).
 my $file = ;
# m modifier allows ^ to match immediately after a newline, and $ to
match preceding a newline
# g modifier is for a progressive match - start next match immediately
after end of previous one
 while ($file =~ /^\s+(\d+).+\n(.+)$/mg) {
  print $1 unless $2 =~ /extractStat/;
 }
}

__DATA__
1   Chaque L Ma Me J V S D  00:20
D:\muse\lotus\notes\extractStat.exe StatA090 j
2   Chaque L Ma Me J V S D  00:21
D:\muse\lotus\notes\extractStat.exe StatA090 m
3   Chaque L Ma Me J V S D  00:22
D:\muse\lotus\notes\extractStat.exe StatA090 h
4   Chaque L Ma Me J V S D  00:23
D:\muse\lotus\notes\extractStat.exe StatB090 j
5   Chaque L Ma Me J V S D  00:27
D:\muse\lotus\notes\extractStat.exe StatPMF090 m
6   Chaque L Ma Me J V S D  00:28
D:\muse\lotus\notes\extractStat.exe StatPMF090 h
7  Aujourd'hui  20:00
D:\muse3\test.exe
8   Chaque L Ma Me J V S D  00:28
D:\muse\lotus\notes\extractStat.exe StatPMF090 h



-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: Pattern match

2004-06-21 Thread Chris Charley

- Original Message - 
From: "Naser Ali" <[EMAIL PROTECTED]>
Newsgroups: perl.beginners
To: <[EMAIL PROTECTED]>
Sent: Monday, June 21, 2004 3:52 PM
Subject: Pattern match


> Hello,
>
> I have an array which was created by slurrping a whole text file. There
are
> certain element in the array after reading the files which contain only
one
> word. I want to only match those array elements which contain a single
word
> and print it. Tried every thing but in vain. I must be doing something
> wrong, can any one please suggest the right way of doing this.
>
> Thanks

Hi Naser,

This can be done without slurping the file into an array first with the
following:

open IN, "<", $myfile or die $!;
print grep /^\S+$/, ;

If you still need to slurp into an array first, the statement above is
changed to:

print grep /^\S+$/, @array;

See perldoc -f grep

Chris



-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: Dates are killing me..

2004-07-07 Thread Chris Charley
Like Luke's solution, but using Date::Simple which comes with the standard
distro of Perl.

#!/usr/bin/perl
use strict;
use warnings;
use Date::Calc qw/ Day_of_Week Add_Delta_Days /;

my @days = (undef, qw/ Mon Tue Wed Thur Fri Sat Sun /);

if ($ARGV[0] !~ /^\d{4}-\d{2}-\d{2}$/) {
 die "Date given must be in -MM-DD form.\n";
}

my @ymd = split /-/, $ARGV[0]; # year,month,day
my $dow = Day_of_Week @ymd;

my $mon = sprintf "%s-%02s-%02s", Add_Delta_Days @ymd, 1 -($dow==1 ?
8:$dow);
my $sun = sprintf "%s-%02s-%02s", Add_Delta_Days @ymd, 7 -($dow==7 ?
0:$dow);

print "Previous Monday: $mon\n";
print "Given Date:  $ARGV[0] $days[$dow]\n";
print "Next Sunday: $sun\n";

Chris



-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: sort of previously ask, but it really a newie

2004-07-13 Thread Chris Charley

- Original Message - 
From: <[EMAIL PROTECTED]>
Newsgroups: perl.beginners
To: <[EMAIL PROTECTED]>
Sent: Tuesday, July 13, 2004 6:13 PM
Subject: sort of previously ask, but it really a newie


> All,
>
> the data below is my end result from my code below, but I am wondering and
> trying to find a better way to print this from an array that may be
> populated with only 1 element or 39 elements?
> as you can see there is only 18 elements, but I cannot have 39 print lines
> if an array is not populated w/39 elements, right?  So I opted for the
> line highlighted to try and print all elements.  The reasoning is if I
> have a file that has max 40 lines in it (1-40) I will need to print all 40
> and anywhere in between 1-40 so instead of having 39 print lines will the
> print map work with my necessary syntax characters; -w 'barcode= or ' ?
> I could have the E strings be $_   thinking to myself  ; ? )
>
> thank you, !
>
>
> edm01:/usr/local/bin/perld>> perl traverse_array.pl testtapes
> -w 'barcode=E00085 or barcode=E00086 or barcode=E00096 or barcode=E00184'
> -w 'barcode=E00245 or barcode=E00271 or barcode=E00293 or barcode=E00351'
> -w 'barcode=E00524 or barcode=E00584 or barcode=E00585 or barcode=E00586'
> -w 'barcode=E00587 or barcode=E00588 or barcode=E00589 or barcode=E00654'
> -w 'barcode=E00702 or barcode=E00771 or barcode=E00876'
>
>
> Here is my code:
>
>
> #!/usr/local/bin/perl -w
> use strict;
> open (FH,"/usr/local/bin/perld/derektapes") or die "cannot open FH: $!
> \n";
> my @a=();
> my $i=0;
> my $ct=0;
> my $or_string=" or ";
> my $w_param="-w '";
> my $b_param="barcode=";
> while () {
> chomp $_;
> $a[$i]=$_;
> $i++;
> }

You can replace that while loop with:
chomp(my @a = );

> #   if ( $ct == 0 ) {
> #   print map {$_, "\n"} @a;

?

> print $w_param; print $b_param; print $a[0];
> print $or_string;print $b_param; print $a[1];
> print $or_string;print $b_param; print $a[2];
> print $or_string;print $b_param; print "$a[3]'\n";
>
> print $w_param; print $b_param; print $a[4];
> print $or_string; print $b_param; print $a[5];
> print $or_string; print $b_param; print $a[6];
> print $or_string; print $b_param; print "$a[7]'\n";
>
> print $w_param; print $b_param; print $a[8];
> print $or_string; print $b_param; print $a[9];
> print $or_string; print $b_param; print $a[10];
> print $or_string; print $b_param; print "$a[11]'\n";
>
> print $w_param; print $b_param; print $a[12];
> print $or_string; print $b_param; print $a[13];
> print $or_string; print $b_param; print $a[14];
> print $or_string; print $b_param; print "$a[15]'\n";
>
> print $w_param; print $b_param; print $a[16];
> print $or_string; print $b_param; print $a[17];
> print $or_string; print $b_param; print "$a[18]'\n"
>

Instead of using multiple lines that do the same thing, you might want to
try the code below.

while (@a) {
my @output = ();
print "-w ";
for (1..4) {
   push @output, "barcode=" . shift @a;
   last unless @a;
}
print join(" or ", @output), "\n";
}

Chris



-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: Is the var recreated in a foreach loop using `my`?

2004-07-16 Thread Chris Charley

- Original Message - 
From: "Rod Za" <[EMAIL PROTECTED]>
Newsgroups: perl.beginners
To: <[EMAIL PROTECTED]>
Sent: Friday, July 16, 2004 10:58 AM
Subject: Is the var recreated in a foreach loop using `my`?


> Hi,
>
> I have a doubt. If i create an array inside a foreach loop using `my`, is
this array recreated
> every time or every time the loop pass by i got a new array?
>
> e.g.:
> _BEGIN_
> #!/usr/bin/perl
> use warnings;
> use strict;
> my @array1 =(1,2,3,4,5,6,7,8,9);
> foreach(@array1){
>  my @array2 = ($_,'a','b','c','d','e'); #is a new the array reated here?
or is the same array?
>  print "$_ = @array2\n";
> }

Very clear answer in the docs.
perldoc perldsc
Read the section 'common mistakes', where this is discussed.
(A piece from that document, below)

Surprisingly, the following dangerous-looking construct will actually
work out fine:

for $i (1..10) {
my @array = somefunc($i);
$AoA[$i] = [EMAIL PROTECTED];
}


Chris



-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Add text to beginning every line

2003-10-07 Thread Chris Charley
Hi

Hope someone can help with this. I used to be able to do it, but now have
forgotten. I want to prepend some text to every line in a file. The program
below:

#!/usr/bin/perl
# prepend.pl - adds line number to beginning of every line in a file
use strict;
use warnings;

while (<>) {
  s/^/Line: $. /;
}

Then, on the command line I type: perl prepend.pl somefile.txt, but
somefile.txt does not have the changes(Line: ).

Thanks for any explanation you may offer.

Chris



-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]



Re: Add text to beginning every line

2003-10-07 Thread Chris Charley

"Chris Charley" <[EMAIL PROTECTED]> wrote in message news:...
[snip]
> while (<>) {
>   s/^/Line: $. /;
> }

Should be (works correctly):

 while (<>) {
   s/^/Line: $. /;
   print;
 }

Then the command could be:perl prepend.pl somefile.txt > somefile.new
which would correctly print to the 'new' file the somefile.txt file with the
line numbers prepended.

Chris



-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]



Re: Debug Help Please

2008-07-09 Thread Chris Charley


- Original Message - 
From: "Andy" <[EMAIL PROTECTED]>

Newsgroups: perl.beginners
To: 
Sent: Tuesday, July 08, 2008 9:31 PM
Subject: Re: Debug Help Please



On Jul 7, 2:16 pm, [EMAIL PROTECTED] (Andy) wrote:

On Jul 7, 11:53 am, [EMAIL PROTECTED] (Rob Dixon) wrote:



> Andy wrote:

> > Funny how when you talk to different people you get different ways of
> > looking at it.

> > One of the Perl guys at my office. told me that I can use
> > use strict;
> > use warnings;

> > but he said , he really doesn't because he wants the script to do 
> > what

> > it needs to do...

> Then he is a fool and should be disregarded. Perhaps he could post to 
> this group

> to explain himself?

> > I have made corrections as you suggested.
> >  I have included.

> > use strict;
> > use warnings;

> > as well as
> >  my $TIME  =$fields[3]

> > However after that ,
> > I still get zero output.

> > Maybe I have this written .

> Have you incorporated all the corrections that John posted in his first
> response? Perhaps you should post your program in its current state so 
> that we

> can take another look.

> Rob

Thank you all for the patience.

I have been doing some debugging...well as much of it as I can handle
with no exp...

This is the current code. I figured out with some help that My
$Dateroot was trying to read
incoming.xferlog.xferlog.csv.

Eventually I want to run "perl andylog.pl and it will Parse all the
xferlogs in the dir.

Thus far with all your help I have it working...now for the tweaks.

I have some lines longer than the other and I have to figure out how
to skip those lines ...

So now I have to figure out how to read them all even longer ones
Tue Apr 29 00:02:13 2008 0 x.x.x.x 521 /home3/FTP-protected/TFN/ixx/
GPSdetail_rpt_20080428_200525.txt b _ i r xxx ftp 0 * c
Tue Apr 29 00:03:40 2008 25x.x.x.x 4246252 /home4/FTP-protected/
DATAWORKS/1234/user_nameEUestimates_2000.zip b _ o r username ftp 0 *
c

use strict;
use warnings;
#Define LogFiles
my $dateroot=$ARGV[0]; # Value should be 2-digit month
my $outgoing="outgoing_xferlog.$dateroot.csv";  # This is for all
files sent to users
my $incoming="incoming_xferlog.$dateroot.csv";  #This is log for
uploads
my $loginsinlog="loginsinlog_xferlog.$dateroot.csv";   # This is where
log users
my $completedlog="completedlog_xferlog.$dateroot.csv";  # All
Completed Sessions
my $failedlog="failedlog_xferlog.$dateroot.csv";   # This is for
all Failures
my %loginsin;
my %completed;
my %failures;
my %incoming;
my %outgoing;

 #Time Measured
print "Started Processing Logfiles for $dateroot at " .
(localtime) ."\n\n";
 #Open Log File Dir to Read .log file(s)
opendir (DIR, ".") or die "$!";

#my @logfiles = grep {/xferlog\.$dateroot/,}  readdir DIR;
my @logfiles = grep {/$dateroot/,} readdir DIR;
close DIR;

   #Start Log Processing
foreach my $logfile (@logfiles) {
   print "Started Processing: $logfile at " . (localtime) ."\n";
   open(FH,"./$logfile") or die "$!";
   while ( my $lines =  ) {
 chomp($lines);
  my @fields = split / /, $lines; #This is where we look for the .
extensions from the file name
#   next if /^#/;
#next if /^(\s)*$/;
  #My Ftp Status Log Values
  my $TIME  =$fields[3]||'NULL';#fields[1],fields[2],fields[3];
  my $YEAR = $fields[4]||'NULL';
  my $IP = $fields[6]||'NULL';
  my $SIZE = $fields[7]||'NULL';#filesize
  my $FILE = $fields[8]||'NULL';#filename and path
  my $DIRECTION = $fields[11]||'NULL'; #Outgoing, Incoming
  my $USERNAME = $fields[13]||'NULL';
  my $STATUS= $fields[17]||'NULL';   #c = completed  i=incomplete
( my $MASKFILE = $FILE ) =~ tr/0-9/#/; #$cnt = tr/0-9//;# count
the digits in $_

  #FailuresThis is where we check for
failures
if ($DIRECTION eq "i" and $STATUS ne "c" ){$failures {$USERNAME}   =
$TIME.",".$YEAR.",".$FILE.",".$IP;}
  #completed sessions
if ($STATUS =~ m "c" ){$completed {$USERNAME}   = $TIME.",".$YEAR.",".
$IP;}

   # incoming
if ($DIRECTION eq "i"  ){$incoming {$USERNAME}   = $TIME.",".$YEAR.",".
$FILE.",".$SIZE.",".$IP;}
  #Outgoing  this is where we log all
outgoing xfers
if ($DIRECTION eq "o"){$outgoing {$USERNAME}   = $TIME.",".$YEAR.",".
$FILE.",".$SIZE.",".$IP;}

   #Masked Options  with file
extensions
#if ($DIRECTION eq "i" and $STATUS eq "c" ){$ {$USERNAME.",".
$MASKFILE} = $FILE.",".$TIME.",".$YEAR.",".$IP.",".$STATUS;}
   }}

   close(FH);

#}
open(OUTPUT, '>', $incoming) or die("Could not open log file.");
for my $key ( sort %incoming) { if ($incoming{$key}) { print OUTPUT
"$key,$incoming{$key}\n";}}
close(OUTPUT);
open(OUTPUT, '>', $outgoing) or die("Could not open log file.");
for my $key ( sort %outgoing) { if ($outgoing{$key}) { print OUTPUT
"$key,$outgoing{$key}\n";}}
close(OUTPUT);
open(OUTPUT, '>', $failedlog) or die("

Re: Handling ignore case and single line in pattern matchin

2008-07-11 Thread Chris Charley


- Original Message - 
From: ""Manasi Bopardikar"" <[EMAIL PROTECTED]>

Newsgroups: perl.beginners
To: 
Sent: Friday, July 11, 2008 4:23 AM
Subject: Handling ignore case and single line in pattern matchin



Hi,

 Does anyone know how to handle ignore case(i) and single line(s) on a
regular expression.


You want the i modifier to ignore case.
http://perldoc.perl.org/perlre.html#Modifiers

Like: m/something/i
This would would match SomeThing, someThing, something, etc...

I don't know what you mean - 'ignore single line(s)'.

Chris


Thanks  and Regards,

Manasi Bopardikar|s/w Engineer|Persistent SystemsLtd




--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/




Re: rand()

2008-07-28 Thread Chris Charley


- Original Message - 
From: "Bobby" <[EMAIL PROTECTED]>

Newsgroups: perl.beginners
To: 
Sent: Monday, July 28, 2008 10:54 AM
Subject: rand()


Hi all,

How do I use the rand function to print out more than one random number for 
an array? In the example script below i have an array @nums with a list of 
numbers; how do i print out more than one random numbers from that list 
(@nums)? Thanks.


You can use 'shuffle' from List::Util.

#!/usr/bin/perl
use strict;
use warnings;
use List::Util qw/ shuffle /;

my $max = 3;
my @nums = ("1","10002","10004","10005","10006","14","150");
my @winner = (shuffle @nums)[0 .. $max - 1];

print "@winner";

'shuffle' does what its name says - shuffles the list items. You will get no 
duplicates.


Chris 




--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/




Re: rand()

2008-07-30 Thread Chris Charley

From: ""Chris Charley""



From: "Bobby" Newsgroups: perl.beginners


Subject: rand()


Hi all,

How do I use the rand function to print out more than one random number 
for an array? In the example script below i have an array @nums with a 
list of numbers; how do i print out more than one random numbers from that 
list (@nums)? Thanks.


You can use 'shuffle' from List::Util.

#!/usr/bin/perl
use strict;
use warnings;
use List::Util qw/ shuffle /;

my $max = 3;
my @nums = ("1","10002","10004","10005","10006","14","150");
my @winner = (shuffle @nums)[0 .. $max - 1];

print "@winner";

'shuffle' does what its name says - shuffles the list items. You will get 
no duplicates.


Chris


Just to clarify a possible misunderstanding. There will be no duplicates 
only if there are no duplicates in the original array. 'shuffle' doesn't 
filter out duplicates - it just shuffles the list.


Chris 




--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/




Re: question about text operation using regex.

2008-08-05 Thread Chris Charley


- Original Message - 
From: ""Remy Guo"" <[EMAIL PROTECTED]>

Newsgroups: perl.beginners
To: "Perl Beginners" 
Sent: Tuesday, August 05, 2008 10:14 PM
Subject: question about text operation using regex.



hi all,
i have a txt log file and i want to delete the 9th character of each line.
how can i do it using regex?...thanks!

-Remy



Ooops. Sent it to the poster by mistake.

You could do it from the command line

perl -pe "8 < length && substr $_,8, 1, ''" logfile.txt > altered_file.txt

Chris



--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/




Re: question about text operation using regex.

2008-08-05 Thread Chris Charley


- Original Message - 
From: "Chris Charley" <[EMAIL PROTECTED]>

To: 
Sent: Tuesday, August 05, 2008 10:45 PM
Subject: Re: question about text operation using regex.




- Original Message - 
From: ""Remy Guo"" <[EMAIL PROTECTED]>

Newsgroups: perl.beginners
To: "Perl Beginners" 
Sent: Tuesday, August 05, 2008 10:14 PM
Subject: question about text operation using regex.



hi all,
i have a txt log file and i want to delete the 9th character of each 
line.

how can i do it using regex?...thanks!

-Remy



Ooops. Sent it to the poster by mistake.

You could do it from the command line

perl -pe "8 < length && substr $_,8, 1, ''" logfile.txt > altered_file.txt

Chris



Just to clarify the substr function here. Following the 1, are 2 *single* 
quotes. This assigns the empty dtring to the 9th position of the string, 
effectively eliminating the 9th character.
Chris 




--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/




Re: question about text operation using regex.

2008-08-06 Thread Chris Charley


- Original Message - 
From: ""Remy Guo"" <[EMAIL PROTECTED]>

Newsgroups: perl.beginners
To: "Perl Beginners" 
Sent: Tuesday, August 05, 2008 10:14 PM
Subject: question about text operation using regex.



hi all,
i have a txt log file and i want to delete the 9th character of each 
line.

how can i do it using regex?...thanks!

-Remy



Ooops. Sent it to the poster by mistake.

You could do it from the command line

perl -pe "8 < length && substr $_,8, 1, ''" logfile.txt > 
altered_file.txt


Chris



Just to clarify the substr function here. Following the 1, are 2 *single* 
quotes. This assigns the empty dtring to the 9th position of the string, 
effectively eliminating the 9th character.

Chris


thanks Chris...but is there any solution that i can put in a script?
Remy

Yes Remy, (but please keep your replies to the group and not me so everyone 
can see and learn!)


open my $log '.<', 'somefile.log' or die "Unable to open file. $!";
while (<$log>) {
substr $_,8, 1, '';  (or you could use regex approach, s/^(.{8})./$1/)
. . .
. . . do whatever, print, etc.
}

You may use either of the two solutions, (substr or regex). However, when 
you use a regex, perl has to start up the regex engine, and there is some 
overhead, (i.e. time) involved.


For the record, my original answer was off by one.
perl -pe "8 < length && substr $_,8, 1, ''" logfile.txt > altered_file.txt

that should be:
perl -pe "9 < length && substr $_,8, 1, ''" logfile.txt > altered_file.txt

That 9 accounts for the newline when taking the length of the line.

Chris



--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/




Re: date info

2008-08-06 Thread Chris Charley


- Original Message - 
From: ""michael wang"" <[EMAIL PROTECTED]>

Newsgroups: perl.beginners
To: 
Sent: Wednesday, August 06, 2008 9:00 AM
Subject: date info



Hi,

if I have something like 20080503, how can I get the date a year ago,
such as  20070503 in perl?

Thanks,

michael



There are many date modules on CPAN such as Date::Calc, DateTime, to name
two. They may be overkill for the simple task you need to solve, but they 
will prevent errors, in this case, concerning leap years.


20080229
20070229  * wrong

Here's an example using the DateTime module. It will correctly account for
leap years.

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

my $str = '20080229';
$str =~ /^(.+)(\d{4})(\d\d)(\d\d)$/;

my $date = DateTime->new( year   => $2,
 month  => $3,
 day=> $4,
   );



print $1, $date->ymd(''), "\n";

$date->subtract( years => 1 );

print $1, $date->ymd(''), "\n";

__END__
*** prints
20080229
20070228

Chris



--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/




Re: Extracting data from log and reformating

2008-08-15 Thread Chris Charley

On Wed, Aug 13, 2008 at 10:05 AM, John W. Krahn <[EMAIL PROTECTED]> wrote:


Kashif Salman wrote:


Greetings,



Hello,

 I have a log file like so, and I am trying to get the date on the next

line
after "Start..." line. So for the log below I'd like to get the output

04/06/05
05/06/05
06/06/05

But I also need to re-format that so the end result becomes:

2005-04-06
2005-05-06
2005-06-06

Any hints?



while ( <> ) {
   /^Start/ && <> =~ /^(\d+)\/(\d+)\/(\d+)/ && print "20$3-$1-$2";
   }


John




 /^Start/ && <> =~ /^(\d+)\/(\d+)\/(\d+)/ && print "20$3-$1-$2";


I understand most of what is going on in the above line except the " && <> 
"

part. Can somebody please explain that? Somehow it searches for "Start" in
the beginning of the line and gets the date from the next line.



The <> operator is in scalar context, so it reads the next line (after 
Start) *and* performs a match on that line. In the match, it captures 3 
groups of your date digits and, if the match succeeds, prints them out in 
the form -mm-dd.


$1 is the first captured digits, $2 is the second capture, etc.

Hope this helps,
Chris 




--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/




Re: local var with no assignment

2008-09-10 Thread Chris Charley


- Original Message - 
From: "oldyork90" <[EMAIL PROTECTED]>

Newsgroups: perl.beginners
To: 
Sent: Wednesday, September 10, 2008 10:19 AM
Subject: local var with no assignment



True or false. (Trying to figure out why this would be done with no
assignment).


The reason is that $/ is initialized to 'undef' inside the block. If you 
were reading a file, this would result in slurping the file.


my $file;
{
   local $/;
   $file = ;
}

Now do something with the file contained in $file.

You can read about this in the FAQ
perldoc -q "How can I read in an entire file all at once?"

Chris


In the following construct, the current value of $/ is
protected by localizing it to the scope of the block.  In this block,
the current value of $/ is not changed.

{
   local $/;
   # do some things here.  The value of $/ is not modified in any of
the code here.
}

Thank you.





--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/




Re: Processing multiple line

2008-09-17 Thread Chris Charley


- Original Message - 
From: ""Aali Naser""



Hello All,

I have a file with the info in the following format;

Start of File=
Server Name: ABCDEF
Manufacturer: Dell
Model: Some Model
Number Of Processors (Includes MultiThread): 2
Maximum Clock Speed: 3 - GHZ
Serial Number: 123456
Proc Usage: (1 Proc Sample Only) 1%
Mem Total: 2 - GB
DeviceID:  C:  Space: 20GB  Used Space: 2GB  UTIL: 61.4991581037678%
DeviceID:  E:  Space: 567.90882304GB  Used Space: 32GB  UTIL:
5.66111272649405%
DeviceID:  F:  Space: 5GB  Used Space: 3GB  UTIL: 7.68405957709316%
Log File Directory: C:\WINDOWS\system32\LogFiles
196.136
Service Pack: 2.0
Connections: 53
HTTPERR Folder:
OS Directory: C:\WINDOWS
System Directory: C:\WINDOWS\system32

Server Name: GHIJKL
Manufacturer: Dell
Model: Some Model
Number Of Processors (Includes MultiThread): 4
Maximum Clock Speed: 3 - GHZ
Serial Number: 123456
Proc Usage: (1 Proc Sample Only) 0%
Mem Total: 2 - GB
DeviceID:  C:  Space: 2GB  Used Space: 9GB  UTIL: 46.0333821902412%
DeviceID:  E:  Space: 5GB  Used Space: 3GB  UTIL: 7.68405957709316%
69.136
Service Pack: 2.0
Connections: 206
HTTPERR Folder:
OS Directory: C:\WINDOWS
System Directory: C:\WINDOWS\system32

End of File=

Each machine entry is seperated by a "" in the
file. I need to put together each machine entry in the following way;

*Server_Name  Manufacture   Model   # of Procs   Serial#  Total_Mem  Disk1
Disk2  Disk3  Service_Pack*

The number of disks could be two or more for each machine and I want to be
able to capture all of them.

Can any one help me with the logic for this type data processing?

Regards,

A



Hello Aali

A couple of questions occurred to me. Is the printout for human eyes or 
might it need to be parsed further? With a variable number of disk drives, 
the printout lines will vary according to the number of drives and make 
further parsing difficult (perhaps impossible). I think you are on the right 
track, (reading your reply to Shawn), but I'm wondering what use the 
printout will be used for.


Chris



--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/




Re: reference question

2008-09-29 Thread Chris Charley

From: "Richard Lee"


one more question on reference,

if say you have sub as below

my @arrayref;

sub do_something {
   my $something = @_;
   open FILE, "$something", or die;
   while () {
my @array = map (split /,/)[1,2,3,5];
push @arrayref, [EMAIL PROTECTED];
   }
  close FILE;
}

my @arrayref_copy = do_something($something);



Let's for a moment forget about my inefficient style and just look at the 
last step.
If I wanted to use @arrayref_copy and pass it into another 
subroutine,should I reference them again?(if file itself was pretty big?)


another_sub([EMAIL PROTECTED]);   <-- is this the right thing to do? or is 
this redundant since array is  already collection of reference?


sub another_sub {

}



You  are confusing the difference between an array (of array refs) and an 
array ref that itself refers to mutiple array refs.


my $aref = [ [1,2], [3,4], [5,6] ];

Now, to dereference the values, you might say

my $value = $aref->[0][1];

Whereas, with an array of arrayrefs, you might
have something like this.

my @array = ([1,2], [3,4], [5,6]);

my $value = $array[0][1];

perldoc perllol explains Perl data structures: arrays of arrays

Chris 




--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/




Re: reference question

2008-09-29 Thread Chris Charley

From: ""Chris Charley""

From: "Richard Lee"


one more question on reference,

if say you have sub as below

my @arrayref;

sub do_something {
   my $something = @_;
   open FILE, "$something", or die;
   while () {
my @array = map (split /,/)[1,2,3,5];
push @arrayref, [EMAIL PROTECTED];
   }
  close FILE;
}

my @arrayref_copy = do_something($something);



Let's for a moment forget about my inefficient style and just look at the 
last step.
If I wanted to use @arrayref_copy and pass it into another 
subroutine,should I reference them again?(if file itself was pretty big?)


another_sub([EMAIL PROTECTED]);   <-- is this the right thing to do? or is 
this redundant since array is  already collection of reference?


sub another_sub {

}



You  are confusing the difference between an array (of array refs) and an 
array ref that itself refers to mutiple array refs.


[rest deleted]

Sorry, misread the problem  :-(

Chris 




--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/




Re: Using a variable in a =~ match??

2008-10-21 Thread Chris Charley
- Original Message - 
From: <[EMAIL PROTECTED]>

Hi all,

Serious noob here (one week into llama 5th ed.).

I'm trying to write a script to pull a specific file from a directory
and search that file for specific phrases. I am having a problem
searching for the file in the directory. If I type in the actual file
name (line 26) I can find the phrase file.zip (line 30). Obviously,
this will only work once. If I use a variable to search for a file I
get nothing. What is the proper format for line 26?I can't use
File::Find so please don't suggest it.  Thx.

#!/usr/bin/perl
 2 use strict;
 3
 4 my $Log_Dir;
 5 my $file;
 6 my $Date;
 7 my $File_Name;
 8 my @array;
 9 my $file_name;
10
11 $Log_Dir = "/var/log/apache/";
12 opendir DH, $Log_Dir or die "Cannot open $Log_Dir: $!";
13 while ($file = readdir DH){
14 push(@array, $file);
15 }
16
17 closedir DH;
18
19 $Date = `date --date=yesterday +%Y%m%d-2400-0`;
20 # The file name always starts with file111-11-23.abctyu_X but the
time stamp changes daily (predictable)
21 # Example Filename: file111-11-23.abctyu_X.20081020-2400-0
22 $File_Name = "file111-11-23.abctyu_X.$Date";
23 print $Date;
24 foreach $file_name (@array){
25 chomp;


chomp is not needed here. Results of readdir do not end with a newline



26 if ($file_name =~ /$File_Name/){


Or:if ($file_name eq $File_Name)



27 open LOGFILE, $File_Name;
28 while (){
29 #Search log file for the word file.zip
30 if(/file.zip/){
31 print "$_\n";
32 }
33 }
34 }
35 }



One thing that probably will cause a problem is 'readdir' returns filenames 
and directories without the path.


So, when you want to open your file, (line 27), unless the current directory 
of the program file is the same as the file you wish to open, it won't open 
it. You need to say like:


open LOGFILE, "$Log_Dir$File_Name" or die "Unable to open $Log_Dir$File_Name 
$!";



From the documentation for readdir:


If you're planning to filetest the return values out of a readdir, you'd 
better prepend the directory in question. Otherwise, because we didn't chdir 
there, it would have been testing the wrong file.


Chris



--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/




Re: Using Heap::Elem

2009-06-30 Thread Chris Charley


- Original Message - 
From: "Ankit Singla" 




Hi,

I'm trying to use Fibonacci heaps to keep  type of objects
sorted. I require the sorting to be over the key. I've only started
out with Perl and can't figure out how to extend the Heap::Elem class
to make this kind of pair objects for use with Heap::Fibonacci. I have
tried reading up the perldocs but it doesn't seem to be a good
starting point for novices like me. Can someone point me to example
code where I can 'watch and learn' or maybe illustrate to me with the
same Heap::Elem extension?

Thanks for your help!

Cheers,
Ankit


Hello,

Heap::Simple's docs show how to order a heap using  pairs.

http://search.cpan.org/~thospel/Heap-Simple-0.13/lib/Heap/Simple.pm

Don't know if this is what you want?

Just a note as you say you are learning Perl. I found it difficult to know 
where
in the perldoc to find the info I needed. I found it easier to eventually 
use them

after reading the best source, 'Programming Perl'. It is well written and
after reading it, I was able to use the perldocs much better.

Chris


--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: mkdir in the mounted partition,please h elp me,thanks

2009-11-18 Thread Chris Charley


- Original Message - 
From: ""gaochong"" 

Newsgroups: perl.beginners
To: 
Sent: Tuesday, November 17, 2009 6:41 AM
Subject: mkdir in the mounted partition,please help me,thanks



#!/usr/bin/perl -w



#Auther:gaochong



use strict;



my @list = (3 .. 9);

my @FA=("FA0001".."FA2000");

sub mk_fa {

   my ($f) = @_;

   foreach my $p (@list) {

   mkdir "/data$p/NRU/$f",0755 or warn "mkdir /data$p/NRU/$f
err:$!";


Hello gaochong,

The mkdir() function will not create any new directories in the 'path' to 
the last new directory


mkdir "/data$p/NRU/$f",0755
 ^^   ^^

The 'data$p' directory must be created before the '$f' directory.

mkdir "/data$p" or warn "mkdir /data$p;

Then, you can say:
mkdir "/data$p/NRU/$f",0755 or warn "mkdir /data$p/NRU/$f

As to a better way, here is another way (without reconstructing the @list 
array).


#!/usr/bin/perl
use strict;
use warnings;
use File::Path; # uses 'mkpath' to make new included dirs in a path

my ($i, @p) = (-1, 3 .. 9);

foreach my $f ("FA0001".."FA2000") {
my $p = $p[++$i % @p];
#mkpath(["/data$p/NRU/$f"], 0, 0755) unless -e "/data$p/NRU/$f";
#symlink "/data$p/NRU/$f","/usr/local/Titan/NRU/$f"
# or warn"symlink /data$p/NRU/$f err:$!";
print "/data$p/NRU/$f\n";
}

This example uses the 'mkpath()' function which *will* construct the entire 
path (unlike the mkdir() function). mkpath() is included in the base perl 
5.8 distribution, so it may be available to you.


Chris 



--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: mkdir in the mounted partition,please h elp me,thanks

2009-11-18 Thread Chris Charley


- Original Message - 
From: ""Chris Charley"" 

Newsgroups: perl.beginners
To: 
Sent: Wednesday, November 18, 2009 12:39 PM
Subject: Re: mkdir in the mounted partition,please help me,thanks




- Original Message - 
From: ""gaochong"" 

Newsgroups: perl.beginners
To: 
Sent: Tuesday, November 17, 2009 6:41 AM
Subject: mkdir in the mounted partition,please help me,thanks


[snip some content]




As to a better way, here is another way (without reconstructing the @list 
array).


#!/usr/bin/perl
use strict;
use warnings;
use File::Path; # uses 'mkpath' to make new included dirs in a path

my ($i, @p) = (-1, 3 .. 9);

foreach my $f ("FA0001".."FA2000") {
my $p = $p[++$i % @p];


There is really no need for the @p array. You could calculate $p like:

my $p = ++$i % 7 + 3;



#mkpath(["/data$p/NRU/$f"], 0, 0755) unless -e "/data$p/NRU/$f";
#symlink "/data$p/NRU/$f","/usr/local/Titan/NRU/$f"
# or warn"symlink /data$p/NRU/$f err:$!";
print "/data$p/NRU/$f\n";
}

This example uses the 'mkpath()' function which *will* construct the 
entire path (unlike the mkdir() function). mkpath() is included in the 
base perl 5.8 distribution, so it may be available to you.


Chris 



--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: a simple question about the line

2009-11-27 Thread Chris Charley


- Original Message - 
From: "Dermot" 

Newsgroups: perl.beginners
To: "John W. Krahn" 
Cc: "Perl Beginners" 
Sent: Friday, November 27, 2009 12:29 PM
Subject: Re: a simple question about the line



2009/11/27 John W. Krahn :


Hello,




$ echo "12
23
34
45
56
67
78" | perl -lpe'$\=--$|?$,:$/'
1223
3445
5667
78


For the benefit of this Luddite, please explain?
Dp.


--$|   toggles between 1 and 0. It is this variable's behavior when (--$| or 
$|--)
$| is initially 0. (NOTE: this behavior doesn't happen with ++$| or 
$|++).


-l  chomps the line input and, for when --$| == 1, prints with $\ = $,
   ($, is by default the empty string). When --$| == 0, prints with $\ 
= $/

($/ is by default = "\n").
-p applies 'print()' as the last statement in the implicit 'while( 
... )'  loop


So. in effect, on the first line in, chomps the line. Then, since $|==1 in 
the first
iteration, prints with a line end equal to $, (by default, the empty 
string).


In the next line, $| will equal 0, so the print will end with $/ (default 
value of "\n")


Chris 



--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: Saturdays in a month

2009-12-23 Thread Chris Charley


- Original Message - 
From: Venkat Saranathan

Newsgroups: perl.beginners
To: Johnson, Reginald (GTS)
Cc: beginners@perl.org
Sent: Tuesday, December 22, 2009 10:27 AM
Subject: Re: Saturdays in a month


You can code a simple time logic to calculate this. Here is a sample code. 
(Bugs included :))



#!/usr/bin/perl

use Time::Local;
use strict;

sub day_in_a_month {
   my ($week_day, $month, $year ) = @_;
   my ($day, $hour, $min, $sec, $time);
   my ($mon, $wday_count);

   $day = 1;
   $hour = $min = $sec = 0;
   $month--;
   $year -= 1900;

   $time = timelocal($sec, $min, $hour, $day, $month, $year);

   for ($mon = $month; $mon == $month; $time += 86400) {
   my ($wday);
   ($mon, $wday) = (localtime($time))[4, 6];
   if ($wday == $week_day) {
  $wday_count++;
   }
   }
   return($wday_count);
}

# 0 - sunday 6- saturday
print day_in_a_month(6, 12, 2009), "\n";


Hello Venkat,

There is a bug in the the 'for' loop above.  :-)

The test to end the loop has to occur just after the line

   ($mon, $wday) = (localtime($time))[4, 6];

Otherwise, it would be possible to be in a new month at this point in the 
code. If the day of week you're seeking is that day, $wday_count would be 
incorrectly incremented. Try adding this line after the one above:


   last unless $mon == $month;

That will allow you to exit the loop when a new month is reached. The for 
loop could then be:


for (;;$time += 86400) {
  .
}

However, I have heard it over and over from good programmers on lists that 
date arithmetic can be tricky. Sometimes a carefully designed module can 
help.


Chris



--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: Regex problem

2009-12-26 Thread Chris Charley


- Original Message - 
From: "Owen" 

Newsgroups: perl.beginners

Hello Owen




To check the date passed with a script, I first check that the date
is in the format 20dd (20 followed by 6 digits exactly)

But the regex is wrong, tried /^20\d{6}/,/^20\d{6,6}?/,/^20\d{6,}?/ and
while a 7 or lesser digit number fails, eg 2009101, a 9 digit number,
like 200910103 does not fail.



unless ( $ARGV[2] =~ /^20\d{6}?/ ) { print




unless ( $ARGV[2] =~ /^20\d{6}$/) ...

If the end of line anchor is used, '$', the regex will accept an 8 digit 
number if it's the only entry in $ARGV[2]


Chris


"$ARGV[2]\tdate format is MMDD, eg 20091031\n"; }


How do I get the regex to fail a 9 digit number


I suppose as a work around, I could say;

unless ((length($ARGV[2]) == 8) and ( $ARGV[2] =~ /^20/){fail}

TIA


Owen 



--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: hash of Arrays

2010-01-18 Thread Chris Charley


- Original Message - 
From: ""Johnson, Reginald (GTS)"" 

Newsgroups: perl.beginners
To: 
Sent: Sunday, January 17, 2010 2:42 PM
Subject: hash of Arrays


I am trying to place the date of each day of the week for each month
that has 5 weeks into a hash. For instance my hash key 'Monday' would
point to an array that has all the dates where Monday is in the fifth
week of the month.
I've got that part going. My problem is I am having a problem accessing
the hash. Data dumper shows me the data is there, but when I try to
access I am doing something wrong.




Hello Reginald

If you make 2 changes, you should be able to view your dates.

$fifthday_hash{$weekday} = \day_in_month($weekday,$mon,$year);
^

That function is returning a ref and then you take a ref of a ref (in your 
code).

Just remove the backslash (in front of the function call).

print "this is key =>$key<= $key $value\n";


$value here is an array ref. To print the values dereference it (with the @ 
sigil)..


print "this is key =>$key<= $key @$value\n";
   ^

You might understand  what's going on better if you read the docs
on references and compound data structures.

- perldoc perlreftut (very short tutorial about references)
- perldoc perldsc (Perl Data Structures Cookbook)

I haven't yet examined your logic for selecting the days you want.
Do you want all dates in the fifth week of a month, by day of week?

Some months have 6 weeks. Do you want to exclude those days?

I wrote a program that collects all days of the week  that
occur 5 times in a month. The logic is simple. For any day of week, a date 
>= 29th
of the month will fall 5 times in a month. February has to be treated 
differently.



Chris




# cat fifthday
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper qw(Dumper);
use Time::Local;

   my @day_Array;
   @day_Array=qw{Monday Tuesday Wednesday Thursday Friday Saturday
Sunday};
   my $weekday;
   my %fifthday_hash;
   my ($sec,$min,$hour,$mday,$mon,$year,$wday,
   $yday,$isdst)=localtime(time);
   my $today = sprintf ("%02d%02d%4d",$mon+1,$mday,$year+1900);
   $mon = $mon+1;
   $year +=1900;

   sub day_in_a_month; #predeclare
   sub day_in_a_month_driver; #predeclare
   foreach $weekday (@day_Array){
   print "this is weeekday $weekday\n";
   $fifthday_hash{$weekday} =
\day_in_month($weekday,$mon,$year);
   }

 print Dumper( \%fifthday_hash);
  while ( my ($key,$value)= each %{fifthday_hash} ) {
   if ($key =~/Monday/) {
   print "this is key =>$key<= $key $value\n";

   }
  }


{snip] rest of his code and disclaimer


--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: Searching First Array in Second Array

2010-01-19 Thread Chris Charley


- Original Message - 
From: "Parag Kalra" 

Sent: Tuesday, January 19, 2010 6:45 AM
Subject: Searching First Array in Second Array



Hello All,

I have 2 arrays. I have written a script that searches each and every 
value

of first array in the second array. Each & every value of Source Array
should occur only once in the target array but it can occur anywhere.

If any of the source value doesn't occur or occur multiple times then the
script reports to the user.

This script is working fine for small arrays.

But I tried executing the script for 2 arrays each of which containing
around 7,00, elements and it is taking very long time.
I am using nested 'for' loops to make this search. How can I optimize it
further to search source array in target array.

Cheers,
Parag



You might get some ideas here (from 'perlfaq4 - Data Manipulation'):

How can I tell whether a certain element is contained in a list or array?

Chris 



--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: Getting the text from a PDF file

2010-02-28 Thread Chris Charley


- Original Message - 
From: ""Ion Pop"" 

Newsgroups: perl.beginners
To: 
Sent: Sunday, February 28, 2010 7:57 AM
Subject: Getting the text from a PDF file



Hello,

I would like to extract the whole text from a PDF document. Can you 
recommend a perl module that can do this under Windows?


I searched on cpan.org and I found very many modules, I tested a few of 
them, but none of them was able to extract the text, which can be seen 
well with Acrobat Reader, but they extracted only garbage, or nothing, or 
just gave an error, or they were incompatible with Windows...


Thank you very much.

IP



Here is a link from this group that explains how to using 'xpdf', (not a 
Perl module).


http://groups.google.com/group/perl.beginners/browse_frm/thread/33e8352da64/ec5b13be708ec05d?hl=en&lnk=gst&q=How+to+pull+Text#ec5b13be708ec05d

Chris 



--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: \1 in character class?

2010-07-14 Thread Chris Charley


- Original Message - 
From: "Bryan R Harris" 

Subject: \1 in character class?





I'm trying to temporarily deal with simple quoted strings by turning:

 data: "this is a string" more: "this is another"

into...

 data: "this is a string" more: "this is another"

TIA.

- Bryan




Here is a way using tbe module Regexp::Common.

#!/usr/bin/perl
use strict;
use warnings;
use Regexp::Common;

while () {
s/($RE{quoted})/ (my $s=$1) =~ s[\s][ ]g; $s/egx;
print;
}

__DATA__
data: "this is a string" more: "this is another"



--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Behavior of minimal when applied to - {1,}? ot to - {0,}?

2011-02-01 Thread Chris Charley

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

$_ = "[][12/21/10 18:39:22] [oasetup] [oasetup] [INFO] Installing the 
HPOvXpl package...";


for my $re (qw{ ^\[(.+?)\] ^\[(.*?)\] }) {
   my ($dt) = /$re/ or die "Horrible death\n";;
   print $re, ' ', "'$dt'", "\n";
}

__END__
C:\Old_Data\perlp>perl t5.pl
^\[(.+?)\] '][12/21/10 18:39:22'
^\[(.*?)\] ''

C:\Old_Data\perlp>

My question in the code above is the '.+?' behavior. I had guessed that it 
would

attempt to match the empty brackets and fail, (because it requires 1 or more
characters). Instead, it captures the right bracket and the left opening 
bracket

and contents (date) of the second bracket pair.

Does the regex first consume a character before checking the next
character to see if it is the first one *after* the expression the '+?' is
applied to. It seems to be the way this regex behaved.

Or does the regex see its going to fail with the empty first bracket pair, 
and so

tries to advance to somehow find a match? This seems pretty vague.

I thought a regex first looks for the next character beyond the
expression the '+?' is applied to, before it consumes any characters?
That is the way the second regex, '.*?', behaved.

Hope it was clear enough.   :-) 



--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: Behavior of minimal when applied to - {1,}? ot to - {0,}?

2011-02-02 Thread Chris Charley



"Rob Dixon"  wrote in message news:4d48bdc7.6050...@gmx.com...

On 01/02/2011 02:30, Chris Charley wrote:


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

$_ = "[][12/21/10 18:39:22] [oasetup] [oasetup] [INFO] Installing the
HPOvXpl package...";

for my $re (qw{ ^\[(.+?)\] ^\[(.*?)\] }) {
my ($dt) = /$re/ or die "Horrible death\n";;
print $re, ' ', "'$dt'", "\n";
}

__END__
C:\Old_Data\perlp>perl t5.pl
^\[(.+?)\] '][12/21/10 18:39:22'
^\[(.*?)\] ''

C:\Old_Data\perlp>

My question in the code above is the '.+?' behavior. I had guessed
that it would attempt to match the empty brackets and fail, (because
it requires 1 or more characters). Instead, it captures the right
bracket and the left opening bracket and contents (date) of the
second bracket pair.

Does the regex first consume a character before checking the next
character to see if it is the first one *after* the expression the
'+?' is applied to. It seems to be the way this regex behaved.

Or does the regex see its going to fail with the empty first bracket
pair, and so tries to advance to somehow find a match? This seems
pretty vague.

I thought a regex first looks for the next character beyond the
expression the '+?' is applied to, before it consumes any characters?
That is the way the second regex, '.*?', behaved.

Hope it was clear enough. :-)


Hey Chris

/.+?/ requires at least one character, so /^\[.+?\]/ will need at least
three characters for a match. The engine will try to match /^\[.\]/ and
fail, then /^\[..\]/, then /^\[...\]/ and so on. Perl doesn't care that
the object string's second character is a ']' - all it has to do is
match /./ and that will do fine. This process continues until the
pattern is long enough to reach the first closing square bracket it
sees, and so comsumes the date/time field to get there.

/.*?/ will match zero characters, so the initial [] fits the bill
immediately. The ? doesn't change the lower bound of the character count
- it simply says to match as few as possible. /.{2,4}/ will match four
characters, while /.{2,4}?/ will match two.

HTH,

Rob

Hi Rob,

Thanks for the good answers from you and Uri. Yes, fulfilling the min of a 
quantifier
before applying the lazy behavior of the ? is what had me stumped. The ? 
doesn't change the lower bound and I was hazy in my mind about that.


Chris 



--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: rmdir

2011-06-24 Thread Chris Charley



"Irfan Sayed"  wrote in message 
news:1308908614.88998.yahoomail...@web125518.mail.ne1.yahoo.com...




hi,
i need to delete some directories recursively which are present at some 
shared location


i tried file::path perl module but the issue with that module is , it is not 
deleting the root/parent dir


it deletes the subdirectories and all the files inside that but not removing 
root dir


here is my code:
$path = "build\\" . "f\$" . 
"\\Store\\build\\Internal_Builds\\Daily_Builds\\Daily\\zoc\\" . 
$hash_fin{$key};


print "$path\n";
print "**\n";
 remove_tree($path,{verbose => 1,safe => 1,keep_root => 0});

now whaat i expect is , module shud delete the dir which is there in $path 
but it does not

plz suggest


regards
irfan

Hello irfan,

why are you using 2 leading backslashes at the start of your path?
$path = "build\\"
Shouldn't there only be 1 backslash?
$path = "\\build\\"


By the way, perl will recognize forward slashes for Windows paths like:
"/build/" . "f\$" . "/Store/build/Internal_Builds/Daily_Builds/Daily/zoc/" . 
$hash_fin{$key};


which will save some typing and looks better as well!

Chris 



--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: Help needed created this data structure

2007-07-09 Thread Chris Charley


- Original Message - 
From: "klute" <[EMAIL PROTECTED]>

Newsgroups: perl.beginners
To: 
Sent: Monday, July 09, 2007 4:20 PM
Subject: Help needed created this data structure



Hi All,

I am new to Perl and was hoping to get advice on
creating the following data structure:

I have an Affiliate Parent Groups, Affiliate Groups,
and Affiliates. Each affiliate has affiliateId,
affiliateName.

I guess what I'd like to have is an array of hashes
where the array would contain Affiliate Parent Groups.
Each item in the array would contain a hash map with
Affiliate Group name as the key and An array of
Affiliates (each having AffiliateId and AffiliateName)
as the value. 


How would I go about creating such structure and
adding values to it in a loop?

Any help will be greatly appreciated!

James


Its hard to see what structure you want without some sample data.
Send some data as it is in the file.

Have you tried any coding yet?

Chris


--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/




Fw: Help needed created this data structure

2007-07-10 Thread Chris Charley


- Original Message - 
From: "Chris Charley" <[EMAIL PROTECTED]>

To: "klute" <[EMAIL PROTECTED]>
Sent: Tuesday, July 10, 2007 7:17 PM
Subject: Re: Help needed created this data structure




- Original Message - 
From: "klute" <[EMAIL PROTECTED]>

Newsgroups: perl.beginners
To: "klute" <[EMAIL PROTECTED]>; 
Sent: Tuesday, July 10, 2007 5:37 PM
Subject: Re: Help needed created this data structure




--- klute <[EMAIL PROTECTED]> wrote:



--- "D. Bolliger" <[EMAIL PROTECTED]> wrote:
> Hello Klute
> 
> (please don't top post to keep the conversation

> readable)
> 
> The following script extracts the information out

of
> your sample data.
> There are no checks if the data format is
"correct"
> (nesting order, additional 
> text).
> 
> It does not result in an array of hashes, but in a

> single hash.
> Modify it if needed :-)
> 
> Dani
> 
> 
> #!/usr/bin/perl
> 
> use strict;

> use warnings;
> 
> use Data::Dumper;
> 
> my %data;
> 
> # holds the current first and second level

> #
> my ($parent_group, $aff_group);
> 
> while () {
> 
># a loop block, so we can use next

>{
>   # skip blank lines
>   /^\s*$/
>  and next;
> 
>   # record current first level

>   /^A.*?: (.*)/ and $parent_group=$1
>  and next;
> 
>   # record current second level

>   /^\s+->.*?: (.*)/ and $aff_group=$1
>  and next;
> 
>   # fill %data, with completed three levels

>   /-->.*?: (\d+).*?: (\w+)/
>  and
> $data{$parent_group}{$aff_group}{$1}=$2;
>}
> 
> }
> 
> print Data::Dumper::Dumper \%data;
> 
> 
> __DATA__

> Affiliate Parent Group: Google
>   -> Affiliate Group: Google Advertiser
>  --> Affiliate (Aff Id: 1, Aff Name: Frank)
>  --> Affiliate (Aff Id: 2, Aff Name: Mary)
> 
>   -> Affiliate Group: Google Publisher

>  --> Affiliate (Aff Id: 3, Aff Name: Lori)
>  --> Affiliate (Aff Id: 4, Aff Name: Mike)
> 
> 
> Affiliate Parent Group: Yahoo

>   -> Affiliate Group: Yahoo Advertiser
>  --> Affiliate (Aff Id: 5, Aff Name: Marlene)
>  --> Affiliate (Aff Id: 6, Aff Name: Larry)
>   -> Affiliate Group: Yahoo Publisher
>  --> Affiliate (Aff Id: 7, Aff Name: Alex)
>  --> Affiliate (Aff Id: 8, Aff Name: Glenn)
> 


Thanks guys for your replies. It works! So what data
structure am I dealing with here? 


$data{$parent_group}{$aff_group}{$1}=$2;

Best,
James



Also, I am not quite sure how to iterate through this
structure and print its contents without using Dumper.
Can anyone help?

Thanks very much!
James



Hello James,

To understand hash references, read the docs.

the perldsc manpage

This is a hash of hash of hash.
One way to get the info could be:

for my $parent (keys %data) {
for my $group (keys %{ $data{$parent} }) {
 my $recs = $data{$parent}{$group};
 while (my ($id, $name) = each %$recs) {
  print "$parent - $group - $id - $name\n";
 }
}
}

Chris


Sent to klute by mistake. Here it is for the list.


--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/




Re: comparing elements of arrays

2007-08-10 Thread Chris Charley


- Original Message - 
From: ""Tony Heal"" <[EMAIL PROTECTED]>

Newsgroups: perl.beginners
To: 
Sent: Friday, August 10, 2007 4:23 PM
Subject: comparing elements of arrays



There has got to be a better way (or more elegant way) to do this.

I have 2 DNS files from bind9. I have removed everything but the relevant 
info I want. That info is as follows:




 A 123.213.123.123

a-stagingA123.123.123.122

 CNAME software.mycompany.com

 A 12.12.12.12



One file (db.cust.com.new) is an updated version of the other 
(db.cust.com).


I want to compare the 2 and create a new file (or update db.cust.com )

I need to remove and log any entry that is in db.cust.com and not in 
db.cust.com.new


I need to log and add any entry in db.cust.com.new that is not in 
db.cust.com.


I need to keep any entry that is in both

I need to log any differences



Most of the logging I have been saving for later.

The script below is what I have so far and it does this:

Reads both files into separate arrays after replacing any white space with 
a single ',' in each element


Rotates thru db.cust.com.new and splits each element into a new array then 
determine if the 1st element of that arrays

exists in the 2nd array

If it does it compares the 2nd element then the 3rd

It print anything that matches all three elements to a file and print to 
screen all differences.




The last else will print new records to the file, but does so for the 
total number of elements in array #2 i.e. 200 time

for each new element



Also this script is only one way. If an element exists in array ! and not 
in array 2 it records that


If an element exists in array 2 and not in array 1 it does not even know 
it and never will.




So my real question is is there a better, more elegant way to do this 
or should I keep going?




Thanks



Tony

[snip code]

Below is one approach to see the differences in 2 arrays (by Randal 
Schwartz).


Chris



The>   How do I compute the difference of two arrays?  How do I compute the
The> intersection of two arrays?

Here's code that doesn't require that uniqueness, and would be a better
candidate for the FAQ:

   my %tally;
   $tally{$_} .= "a" for @array_a;
   $tally{$_} .= "b" for @array_b;
   my @union = keys %tally;
   my @intersection = grep $tally{$_} =~ /ab/, @union;
   my @a_not_b = grep $tally{$_} =~ /a$/, @union;
   my @b_not_a = grep $tally{$_} =~ /^b/, @union;

print "Just another Perl hacker,"; 




--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/




Re: Ability to do numeric and alpha sort in one pass on data which is compirsed of both

2007-08-14 Thread Chris Charley


- Original Message - 
From: ""Wagner, David --- Senior Programmer Analyst --- WGO"" 
<[EMAIL PROTECTED]>

Newsgroups: perl.beginners
To: 
Sent: Tuesday, August 14, 2007 1:06 PM
Subject: Ability to do numeric and alpha sort in one pass on data which is 
compirsed of both



I am attempting to sort data which has  a combination of both numeric
and alpah numeric data. Now it would not be so bad, but the numeric data
can be either 9 or 10 characters in length and no leading zero is
supplied in the numbers.

I have supplied some code I am playing with, but running into a mental
block in attempting to get it sorted.

Any thoughts on how to approach would be greatly appreciated?
Running on XP AS 5.8.8.Build 820. Trying to use core Perl verses adding
any modules if possible.


[snip code]

Hello Wags,
I approached the problem by creating a sortstring stored as the value in the 
hash. By normalizing the input (to have a leading zero if there is only 9 
digits), an ascii compare (cmp) can be used on all the data, whether all 
digits, or alphanumerical. The code for this is in the middle of the file 
read loop and the output code now does a standard cmp on the values of the 
hash.


Chris


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

my %MPI = ();
my $MyProInfo = \%MPI;

my $MyIn = 0;
my $MyOut = 0;

my $MyWrkKey;
while (  ) {
   chomp;
   $MyIn++;
   next if ( /^\s*(#|$)/ );
   next if ( /^\s/ );
   $MyWrkKey = substr($_,0,13);
   my $sortstr;
   if (index($_, ' ') == 9) { # (that's a space in the quotation marks)
$sortstr = substr $_, 0, 9;
$sortstr = '0' . $sortstr unless $sortstr =~ /\D/;
   }
   else {
$sortstr = substr $_, 0, 10;
   }
   $MyProInfo->{$MyWrkKey} = $sortstr;
   $MyOut++;
}


foreach my $MyPrtKey (sort {$MyProInfo->{$a} cmp $MyProInfo->{$b}} keys 
%$MyProInfo) {

   printf "MyPrtKey: %s\n", $MyPrtKey;
}



--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/




Re: modification

2007-08-20 Thread Chris Charley


- Original Message - 
From: "Ken Foskey" <[EMAIL PROTECTED]>

Newsgroups: perl.beginners
To: "beginners perl" 
Sent: Monday, August 20, 2007 10:47 AM
Subject: modification




I have a piece of code that I am assured works and I cannot see why it
would.  Code is supposed to force undefined, zero and all space to
numeric zero to stop printf being undefined.

foreach my $value (@array) {
   if( ! $value or $value = "  " ) {
   $value = 0;
   }
}

Will this actually work, or as I suspect do nothing because $value is a
copy.


Hello Ken
In a for(or foreach) loop, if $value is changed, the actual array element is 
changed;

Best described here:
http://perldoc.perl.org/perlsyn.html#Foreach-Loops-for-foreach
Chris


The root cause of the problem is that the array is read from a file with
a simple substr

 $array[0] = substr( $_, 256, 6 );

Despite documented standards some values are simply filled with blanks.

Then rebuilt with a printf "%06d", $array[0]; and this causes a non
numeric warning.

Is there a 'better' way to do this.

--
Ken Foskey
FOSS developer





--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/




Re: working with 3-dimensional array

2007-09-13 Thread Chris Charley


- Original Message - 
From: "Tim McGeary" <[EMAIL PROTECTED]>



Hi all,

I'm trying to read in two file sets of library records, compare a regex 
that I find in different lines of each set of records, and then copy one 
whole line over to the other when a match is found.


?


To do this, I am trying to use a 3-dimensional array:
[fileset][record][line]

I think that I am reading and pushing the arrays onto the other arrays 
correctly, but when I'm traversing the arrays to do the conditionals, I am 
getting uninitialized value warnings, which seems like I'm either not 
traversing correctly OR I'm not really pushing the data onto the arrays 
properly.


This is my whole script below.  Does anyone see what I'm doing wrong?

Thanks,
Tim


Hi Tim

It would be helpful if you could post about 15 lines from each file so we 
could see what kind of data you're parsing.


Also, how many lines in the diss.flat file could have a field value of .001? 
Are there more than 1?


Same thing for ludiss.flat. In addition, is there more than 1 line with a 
field of ..856?


Reading your code, it seems you bail out after finding the (fisrt?) match 
but if there are more lines with these values , what about them?


Perhaps if you tried to explain what you are trying to do again , then a 
solution could be found.


I found a problem with your arrays, but even before you start thinking about 
what kind of data structure you want to use here, a clearer idea of whats in 
the file and how you want to process it could precede your choice of arrays 
(or perhaps a hash).


Chris




--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/




Re: working with 3-dimensional array

2007-09-13 Thread Chris Charley


- Original Message - 
From: ""Chris Charley"" <[EMAIL PROTECTED]>

Newsgroups: perl.beginners
To: 
Sent: Thursday, September 13, 2007 11:55 PM
Subject: Re: working with 3-dimensional array




- Original Message - 
From: "Tim McGeary" <[EMAIL PROTECTED]>



Hi all,

I'm trying to read in two file sets of library records, compare a regex 
that I find in different lines of each set of records, and then copy one 
whole line over to the other when a match is found.


?


To do this, I am trying to use a 3-dimensional array:
[fileset][record][line]

I think that I am reading and pushing the arrays onto the other arrays 
correctly, but when I'm traversing the arrays to do the conditionals, I 
am getting uninitialized value warnings, which seems like I'm either not 
traversing correctly OR I'm not really pushing the data onto the arrays 
properly.


This is my whole script below.  Does anyone see what I'm doing wrong?

Thanks,
Tim


Hi Tim

It would be helpful if you could post about 15 lines from each file so we 
could see what kind of data you're parsing.


Also, how many lines in the diss.flat file could have a field value of 
.001. ? Are there more than 1?


Same thing for ludiss.flat. In addition, is there more than 1 line with a 
field of ..856. ?


Reading your code, it seems you bail out after finding the (fisrt?) match 
but if there are more lines with these values , what about them?


Perhaps if you tried to explain what you are trying to do again , then a 
solution could be found.


I found a problem with your arrays, but even before you start thinking 
about what kind of data structure you want to use here, a clearer idea of 
whats in the file and how you want to process it could precede your choice 
of arrays (or perhaps a hash).


Chris



Me again  :-)

Don't know if my reply was critical - dicn't mean it to be. But, following 
your code through the if blocks made me wonder and raise those questions. I 
guess what I saw there was something like this:


Read the 2 files into 2 arrays.

Then, for each line of the one file, go through all the lines of the second 
file until a match was found.
Then, exit the either the inner loop or outer loop and start again with the 
next line from the first file looking for another match. For the second 
file, you look for either a .001. or .856. field in the same line and it 
can't be both. so I'm wondering what the code is supposed to do.


Anyhow, I guess I'm not sure what it is the plan to look for matches.
If you want to compare groups of lines in one file (delimited by the lines: 
'*** DOCUMENT BOUNDARY ***' and 'FORM=MARC'). Is it important to group these 
lines into a record delimited by those lines?


With some additional questions,
Chris 




--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/




Re: System

2007-09-22 Thread Chris Charley


- Original Message - 
From: "Somu" <[EMAIL PROTECTED]>

Newsgroups: perl.beginners
To: 
Sent: Friday, September 21, 2007 11:27 AM
Subject: System



About that PID problem, i found a program in Windows named tasklist,
it prints all the processes running on the system with its id. I used
the system command to execute the tasklist, like as

my $data = system "tasklist" ;

but i got nothing in $data. How can i get the data from the system 
command?


Hi Somu

You can't capture data with 'system'.


From the documentation for system:


This is not what you want to use to capture the output from a command, for 
that you should use merely backticks or qx//, as described in `STRING` in 
the perlop manpage. Return value of -1 indicates a failure to start the 
program or an error of the wait(2) system call (inspect $! for the reason).


Chris 




--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/




Re: split based on n number of occurances of a character

2007-10-26 Thread Chris Charley


- Original Message - 
From: ""Jeff Pang"" <[EMAIL PROTECTED]>

Newsgroups: perl.beginners
To: "Mahurshi Akilla" <[EMAIL PROTECTED]>
Cc: 
Sent: Friday, October 26, 2007 6:51 AM
Subject: Re: split based on n number of occurances of a character



On 10/26/07, Mahurshi Akilla <[EMAIL PROTECTED]> wrote:

Is there an easy way (without writing our own proc) to split a string
based on number of occurances of a character ?

for example:

$my_string = "a;b;c;d;e;f;g;h"

@regsplitarray = split (/;/, $my_string)   splits based on every 1
occurance of ";"

what if i want it to do 2 at a time ?  e.g. $regsplitarray[0] =
"a;b" .. $regsplitarray[1] = "c;d" .. and so on..

In this example, I used 2..  It could be n in general.  Is there a way
to do this without writing our own procedure ?


--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/




using a regex is may suitable.

$ perl -e '$x= "a;b;c;d;e;f;g;h";@re=$x=~/(\w+;\w+);{0,1}/g;print "@re"'
a;b c;d e;f g;h




The regexpr that Jeff provided will work if there is an even amount of
items, but not if the number of items is odd. The regular expression would
miss the 'i' at the end of the string (below).

my $my_string = "a;b;c;d;e;f;g;h;i";
my @re= $my_string =~/(\w+;\w+);{0,1}/g;

print join "\n", @re;

a;b
c;d
e;f
g;h


To capture the lone 'i' at the end of the string, you would need a regexpr
like this:

my @pairs = $my_string =~ /(\w+(?:;\w+){0,1})/g;
print join "\n", @pairs;

a;b
c;d
e;f
g;h
i

The regular expression above can be explained as:

* one or more word chars, \w+
* plus 0 or 1 groups of a semicolon plus one or more word chars:
(?:;\w+){0,1}
* the second parenthesis group, (?:...), just groups the second group and
doesn't capture, but instead, is a group to apply the 0 or 1, {0,1},
quantifier to. The ?: notation says don't capture.
* the overall group, including the first set of word chars, is captured
between the first left parens, '(', and the final right parens, ')'.

Also, to capture groups of 3, for example, you would only need to change the
quantifier from {0,1} to {0,2}.
my @threes= $my_string =~ /(\w+(?:;\w+){0,2})/g;
print join "\n", @threes;

a;b;c
d;e;f
g;h;i


(From perldoc perlrequick)

\w is a word character (alphanumeric or _) and represents:  [0-9a-zA-Z_]

Mahurshi, you may want to read the manual sections to understand regexps. At
the command line type:
perldoc perlrequick
perldoc perlretut

Hope this helps,
Chris


--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/




Re: user arguments, oracle - insert, delete and drop!

2008-01-11 Thread Chris Charley


- Original Message - 
From: "perlmunky" <[EMAIL PROTECTED]>

Newsgroups: perl.beginners
To: 
Sent: Friday, January 11, 2008 9:11 AM
Subject: user arguments, oracle - insert, delete and drop!



Hi List,

I am in the process of making a web service which will (at some point) 
query

an oracle DB with some user supplied text.  Currently the page allows the
user to select the information in the insert from a tick box, the tables
from a list and the conditional they can choose and then enter associated
text.

I realise that this is not smart, at least without any parameter checking.
I need a way of making the information 'safe' - avoid sql injections etc. 
I

have tried using $dbh->quote($string) but this creates errors if the key
word entered by the users is null - as oracle thinks this is not a 
keyword.


hints, tips and solutions accepted :)

I don't have admin rights and can't install any modules that aren't 
already

available.  The project is running under perl catalyst.

Thanks in advance


See this colimn by Randal L. Schwartz. It descibes injection attacks.
http://www.stonehenge.com/merlyn/UnixReview/col58.html 




--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/




Re: PPM Repository

2008-04-04 Thread Chris Charley


- Original Message - 
From: "Jim" <[EMAIL PROTECTED]>

Newsgroups: perl.beginners
To: 
Sent: Friday, April 04, 2008 6:04 AM
Subject: PPM Repository



Hi all,

I am looking to easily install some modules, like for example
Win32::Clipboard, but they don't show with teh standard modules on
ActiveState's repository.

Are there a couple of better ones I can add?

Thanks for your time

Jim



There are some additional depositories mentioned in the HTML documentation 
that comes with ActiveState's Perl.


To navigate there: first select perl in the left hand frame (which brings up 
*Welcome to ActivePerl*). Then select Perl Package Manager->Where are the 
package repositories?


There may be other sources, but these are ones I'm aware of. And I believe 
Dave Roth's repository has most of the Win32* modules.


Chris 




--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/




Re: comparing two binary numbers

2008-05-11 Thread Chris Charley


- Original Message - 
From: ""Johnson Lau"" <[EMAIL PROTECTED]>

Newsgroups: perl.beginners
To: 
Sent: Sunday, May 11, 2008 1:09 AM
Subject: comparing two binary numbers



Dear all,

I need to compare two binary numbers and need perl to return the
number of matching bits.

For example:

$aaa = "1000";
$bbb = "00101100";

In this case, the number of matching bits is 6.

I know I could split the strings and compare the bits one by one.
However, is there any faster functions for this? I need to compare
millions of such strings with 1000 bits for each.

Thanks a lot!!

Johnson Lau


After reading the others' replies, I believe this xor operation will do what 
you want;


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

my $aaa = "1000";
my $bbb = "00101100";

my $same = ($aaa ^ $bbb) =~ tr/\0//;

print $same;


Chris 




--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/




Re: Taint mode and SQL

2006-03-25 Thread Chris Charley


- Original Message - 
From: "Tom Allison" <[EMAIL PROTECTED]>

Newsgroups: perl.beginners
To: "beginners perl" 
Sent: Saturday, March 25, 2006 1:33 PM
Subject: Taint mode and SQL


I was looking at some code of mine and it seems that there is a potential 
for a problem here that I wasn't aware of.


I'm using CGI and DBI together and found that I can do the following under 
Taint just fine.


my $username = $q->param('username');
and later one...
my $sql = "select .. from .. where username = '$username'";
my $ref = $dbh->selectrow_arrayref($sql)

with out any complaints.

I would have expected this to require me to do something to untaint the 
value in $username.


Doesn't this lead to SQL injections?

Or is that only on update/insert/delete queries instead of select.


I don't know if this will be helpful, but here is a column by Randal 
Schwartz describing SQL injection attacks.


http://www.stonehenge.com/merlyn/UnixReview/col58.html



--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: increment operator

2006-04-08 Thread Chris Charley


- Original Message - 
From: "Alan_C" <[EMAIL PROTECTED]>

Newsgroups: perl.beginners
To: 
Sent: Saturday, April 08, 2006 8:47 PM
Subject: increment operator



Hi,

[EMAIL PROTECTED]:~$ this_pl_script word array print

$size prints at 3 and it finds each of the 3 words entered on the command
line.

But the order of the printed out found words isn't what I expected -- I 
had

expected the ouput order of 1st word, 2nd word, 3rd word as entered on the
command line.

I don't need any certain order.  But I don't understand why it prints out 
the
found words in the order that it does and/or I've got something wrong in 
the

code.


The order of the found words depends on which line you are reading from the 
file (DATA in your example).  The way your input file (DATA) is, it finds 
'array' in line 1, and doesn't find 'word' until
until line 8 (even though 'word' comes before 'array' in your command line 
arguement list.


I think that is what you want to know.



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

my $size = @ARGV;
print $size, "\n";

my @search4 = @ARGV;# keywords
# to @search4 so can now set @ARGV to a file to read
# (since this is example which instead uses )
my @list;
my $linename;
while () {
   @list = split;
   $linename = shift @list;
   foreach (@list) {
   for ( my $i = 0 ; $i < $size ; $i++ ) {
   if (/$search4[$i]/) {
   print "srchword '$search4[$i]' found in:\n";
   print $linename, "\n";
   print @list, "\n\n";
   }
   }
   }
}
__DATA__
line1 map array arrays
line2 snippet replace in files
line3 capture output including errors:
line4 date prefix onto file name
line5 snippet slurp local
line6 dir operations rename files in dir cp mv very good way
line7 print character multiplied
line8 word matches
line9 array of hashes

--
Alan C. 




--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: increment operator

2006-04-08 Thread Chris Charley


- Original Message - 
From: "Alan_C" <[EMAIL PROTECTED]>

Newsgroups: perl.beginners
To: 
Sent: Saturday, April 08, 2006 8:47 PM
Subject: increment operator



Hi,

[EMAIL PROTECTED]:~$ this_pl_script word array print

$size prints at 3 and it finds each of the 3 words entered on the command
line.

But the order of the printed out found words isn't what I expected -- I
had
expected the ouput order of 1st word, 2nd word, 3rd word as entered on the
command line.

I don't need any certain order.  But I don't understand why it prints out
the
found words in the order that it does and/or I've got something wrong in
the
code.


The order of the found words depends on which line you are reading from the
file (DATA in your example).  The way your input file (DATA) is, it finds
'array' in line 1, and doesn't find 'word' until line 8 (even though 'word'
comes before 'array' in your command line arguement list).

I think that is what you want to know.

Chris



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

my $size = @ARGV;
print $size, "\n";

my @search4 = @ARGV;# keywords
# to @search4 so can now set @ARGV to a file to read
# (since this is example which instead uses )
my @list;
my $linename;
while () {
   @list = split;
   $linename = shift @list;
   foreach (@list) {
   for ( my $i = 0 ; $i < $size ; $i++ ) {
   if (/$search4[$i]/) {
   print "srchword '$search4[$i]' found in:\n";
   print $linename, "\n";
   print @list, "\n\n";
   }
   }
   }
}
__DATA__
line1 map array arrays
line2 snippet replace in files
line3 capture output including errors:
line4 date prefix onto file name
line5 snippet slurp local
line6 dir operations rename files in dir cp mv very good way
line7 print character multiplied
line8 word matches
line9 array of hashes

--
Alan C.




--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: Mismatch Positions of Two Ambiguous Strings

2006-04-27 Thread Chris Charley


- Original Message - 
From: "Wijaya Edward" <[EMAIL PROTECTED]>

Subject: Mismatch Positions of Two Ambiguous Strings




Hi,
I have two strings that I want to compute the number of mismatches between 
them. These two strings are of the "same" size. Let's call them 'source' 
string and 'target' string. Now, the problem is that the 'source' and 
'target' string may come in ambiguous form, meaning that in one position 
they may contain more than 1 (upto 4) characters. The ambiguous position 
is marked with square bracketed [ATCG] region.

The example is as follows:

Example 1 (where the source is ambiguous):

my $source1  = '[TCG][AT]'; # ambiguous
my $target1   = 'AC'; # No of mismatch = 2  on position 1 and 6
my $target2  = 'TC'; # No of mismatch = 1  on position 6 only


Example 2 (where the source is NOT ambiguous):

my $source2  =  'TT'; # not-ambiguous
my $target1  = 'AC'; # No of mismatch = 2  on position 1 and 6
my $target3  = 'TT'; # No of mismatch = 0  all position matches


Example 3 (where both source and target are ambiguous)
my $source1  = '[TCG][AT]'; # ambiguous
my $target1   = 'A[CT]'; # ambiguous, no of mismatch = 1  only 
at position 1


For example I can use bitwise operator to do it.

I have no problem when dealing with Example 1 and 2 above.
But I'm stuck with example 3, where both source and target is ambiguous.


Here is the current snippet I have, which doesn't do the job:


[snip]

Hello Edward

This code will handle ambiguous cases in the source, target or both or 
neither. I 'lifted' the expand_fasta funtion mostly from Perlmonks, (the 
link is given in the comments on that section of code). I that code is 
pretty much bulletproof. I tested all your cases and came up with good 
answers, as well as additional cases I constructed (where all characters 
mismatched, for example).


This did not provide the positions that the mismatches occurred at, but I 
didn't think that was what you were after. If it is, the mismatches() 
function would need to be different.


Chris



#!/usr/bin/perl
use strict;
use warnings;
use Set::CrossProduct;

my $source = '[TCG][AT]';
my $sources = expand_fasta($source);

my $target = 'A[CT]';
my $targets = expand_fasta($target);

my $mismatches = mismatches($sources, $targets);
print $mismatches;

# 'lifted' most of this function, (w/one correction) from Perlmonks
# http://www.perlmonks.org/index.pl?node_id=510756
sub expand_fasta {
my $str = shift;
my $strings = [];
my @wildcard;
$str =~ s{ \[ ([ATCG]+) \] }{ push @wildcard, $1; "%s"; }xge;

# if string was ATC[TG]CC, then
# now your string looks like "ATC%sCC"

if( @wildcard ) {
my @set = map [ split //, $_ ], @wildcard;

# now @set contains ( [ 'T', 'G' ] )
# and we weave each possible combination
# into the %s placeholders in $str

if (@set > 1) { # this if/else needed for crossproduct to work OK
 my $xp = Set::CrossProduct->new( [EMAIL PROTECTED] );
 while( my @tuple = $xp->get ) {
 push @$strings, sprintf $str, @tuple;
 }
}
else {
 for (@{$set[0]}) {
  push @$strings, sprintf $str, $_;
 }
}
}
else {
push @$strings, $str;
}
return $strings;
}




sub mismatches {
my ($source_ary, $target_ary) = @_;
my $length = length $source_ary->[0];
my $mismatch = $length; # mismatches starts out equal to length of word

for my $src (@$source_ary) {
 for my $target (@$target_ary) {
  my $compare = $src ^ $target;
  my $matches = $compare =~ tr /\0//;
  my $no_match = $length - $matches; # number of mismatches
  if ($no_match == 0) {
   return 0;
  }
  else {
   if ($no_match < $mismatch) {
$mismatch = $no_match;
   }
  }
 }
}
return $mismatch;
}



--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: Mismatch Positions of Two Ambiguous Strings

2006-04-27 Thread Chris Charley


- Original Message - 
From: ""Chris Charley"" <[EMAIL PROTECTED]>

Newsgroups: perl.beginners
To: 
Sent: Thursday, April 27, 2006 5:07 PM
Subject: Re: Mismatch Positions of Two Ambiguous Strings




- Original Message - 
From: "Wijaya Edward" <[EMAIL PROTECTED]>

Subject: Mismatch Positions of Two Ambiguous Strings




Hi,
I have two strings that I want to compute the number of mismatches 
between them. These two strings are of the "same" size. Let's call them 
'source' string and 'target' string. Now, the problem is that the 
'source' and 'target' string may come in ambiguous form, meaning that in 
one position they may contain more than 1 (upto 4) characters. The 
ambiguous position is marked with square bracketed [ATCG] region.

The example is as follows:

Example 1 (where the source is ambiguous):

my $source1  = '[TCG][AT]'; # ambiguous
my $target1   = 'AC'; # No of mismatch = 2  on position 1 and 6
my $target2  = 'TC'; # No of mismatch = 1  on position 6 only


Example 2 (where the source is NOT ambiguous):

my $source2  =  'TT'; # not-ambiguous
my $target1  = 'AC'; # No of mismatch = 2  on position 1 and 6
my $target3  = 'TT'; # No of mismatch = 0  all position matches


Example 3 (where both source and target are ambiguous)
my $source1  = '[TCG][AT]'; # ambiguous
my $target1   = 'A[CT]'; # ambiguous, no of mismatch = 1 
only at position 1


For example I can use bitwise operator to do it.

I have no problem when dealing with Example 1 and 2 above.
But I'm stuck with example 3, where both source and target is ambiguous.


Here is the current snippet I have, which doesn't do the job:


[snip]

Hello Edward

This code will handle ambiguous cases in the source, target or both or 
neither. I 'lifted' the expand_fasta funtion mostly from Perlmonks, (the 
link is given in the comments on that section of code). I that code is 
pretty much bulletproof. I tested all your cases and came up with good 
answers, as well as additional cases I constructed (where all characters 
mismatched, for example).


This did not provide the positions that the mismatches occurred at, but I 
didn't think that was what you were after. If it is, the mismatches() 
function would need to be different.


Chris


Forget my last post. D Bollinger's solution is succinct and to the point!

Chris



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




Re: Searching problem in list of lists

2006-05-17 Thread Chris Charley


- Original Message - 
From: <[EMAIL PROTECTED]>

Newsgroups: perl.beginners
To: "David Romano" <[EMAIL PROTECTED]>
Cc: 
Sent: Wednesday, May 17, 2006 8:02 AM
Subject: Re: Searching problem in list of lists

Hello,
On 5/17/06, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> Hello,
>
> I'm not a Perl guru so I (still) have problems :-)
> I use the following date structure, quite "classic" : a list of lists. 
> I

have
> two instances of this structure, let's take a simple example :
>
> list 1 : [ [toto,tata],[toto,titi] ]
> list 2 : [ [toto,tutu],[tata,titi],[toto,titi] ]
>
> My question is :
> is there an efficient way to make this kind of research :
>
> I want to know if [toto,titi] from list 1 is present in list 2.



I'd use List::Compare from the CPAN.


Your idea was looking great. But what a pity, after some tests, 
List::Compare

doesn't seem to handle this kind of structure. :-(

Selon David Romano <[EMAIL PROTECTED]>:




HTH,
David


I was able to get results using List::Compare as suggested by D Romano.

HTH
Chris

#!/usr/bin/perl
use strict;
use warnings;
use List::Compare;

my @list1 = ( ['toto','tata'],['toto','titi'] );
my @list2 = ( ['toto','tutu'],['tata','titi'],['toto','titi'] );

my $i = 1;
for my $L1 (@list1) {
for my $L2 (@list2) {
 my $lc = List::Compare->new($L1, $L2);
 my @LorRonly = $lc->get_LorRonly;
 print $i++, ": @LorRonly\n";
}
}

__END__

C:\perlp>perl t5.pl
1: tata tutu
2: titi toto
3: tata titi
4: titi tutu
5: tata toto
6:

C:\perlp> 




--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: split doubt

2006-05-25 Thread Chris Charley


- Original Message - 
From: ""Saurabh Singhvi"" <[EMAIL PROTECTED]>

Newsgroups: perl.beginners
To: "Perl FAq" 
Sent: Thursday, May 25, 2006 3:38 PM
Subject: split doubt



Hi

the format of split() defines that one
can split a string into a fixed number
of specifies strings. for eg

($login, $passwd, $remainder) = split(/:/, $_, 3);

Now, the thing is, it splits on first 3 parts.
Can i do the reverse?? as in instead of the output
being the first 3 parts of split, the last 3 parts of
split for the same string.

thanks
Saurabh



Sure, the code below will do that.

Chris


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

my $string = "a;b;c;d;e;f";

my ($stuff1, $stuff2, $stuff3) = (split /;/, $string)[-3..-1];

print "$stuff1 $stuff2 $stuff3\n";

__END__
this prints...

d e f



--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: parsing a CSV file with more fields than column names

2006-06-08 Thread Chris Charley


- Original Message - 
From: ""RICHARD FERNANDEZ"" <[EMAIL PROTECTED]>

Newsgroups: perl.beginners
To: 
Sent: Thursday, June 08, 2006 11:17 AM
Subject: parsing a CSV file with more fields than column names


Hello All,

I'm just trying to get some ideas for the best way to approach this...

I have a CSV file whose first line is a header. According to this header
there should be 17 values per line. Unfortunately this is not the case.
It seems that the first 16 header values match up with the first 16
values in each line, but for the 17th header item, there may be 1 or
more comma separated values associated with it! Here is a sample line
with header:

Num,Env Num,Envelope,Transaction,Lockbox,Date,Time,Batch,Batch
Item,Check,Check Amount,ABA/RT,Account Num,Check Num,Check
Image,Envelope Image,Page Images

1,1,G-999,G-999,SFC-99,2006/06/01,11:00,999,9,9,$.99,999
99,,99,9,9,23,24,25,26,27 



As you can see the 17th value is "23", but really there are 5 values
associated with "Page Images", 23-27.

I've been playing with Tie::Handle::CSV, but I don't see a way to have
it pick up more that one value per hash key. What I need is a way to
specify "all remaining values" a la split, perhaps with an array ref.

Maybe Tie::Handle::CSV isn't the best choice? 


Any thoughts are appreciated.

TIA

richf

Hello Rich

See docs for perlfunc, specifically split.

Especially, the form for split
   'split /PATTERN/,EXPR,LIMIT'

By setting the limit, you will be able to solve the problem.

Chris


--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: Regex find and replace - delete line

2006-07-24 Thread Chris Charley


- Original Message - 
From: ""John W. Krahn"" <[EMAIL PROTECTED]>

Newsgroups: perl.beginners
To: "Perl Beginners" 
Sent: Sunday, July 23, 2006 4:33 PM
Subject: Re: Regex find and replace - delete line



James Turnbull wrote:

Hi all


Hello,


This feels like a really dumb question but doing a regex find and
replace is it possible to delete a line?  For example,

for (@file) {
  s/foo//g;
}

which equates to:

for each element in array 'file' if you find 'foo' then replace it with
null.

I then write the array to a file (using Tie::File) and it leaves a blank
line where the element containing 'foo' was like:

null
foo1
foo2
foo3

Perhaps I am confabulating two ideas here?  Is there a way to walk
through an array and find a particular array element and delete it
rather than replace it with null (and then write it out to a file using
Tie::File)?


As you have seen when using Tie::File removing the contents of a line do 
not

remove that line.  You have to splice the tied array:


my $line_to_remove;

for my $i ( 0 .. $#file ) {
 $line_to_remove = $i if /foo/;
}

splice @file, $line_to_remove, 1;


If you have more than one line to remove:


my @lines_to_remove;

for my $i ( 0 .. $#file ) {
 unshift @lines_to_remove, $i if /foo/;
}

for ( @lines_to_remove ) {
 splice @file, $_, 1;
}


And if you want to do it with one loop:


for my $i ( reverse 0 .. $#file ) {
 splice @file, $i, 1 if /foo/;
}


Hi John

Shouldn't the above read like:

for my $i ( reverse 0 .. $#file ) {
 splice @file, $i, 1 if $file[$i] =~ /foo/;

Chris





John
--
use Perl;
program
fulfillment 




--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: passing a list as a variable

2006-07-24 Thread Chris Charley


- Original Message - 
From: ""Ryan Moszynski"" <[EMAIL PROTECTED]>

Newsgroups: perl.beginners
To: 
Sent: Monday, July 24, 2006 12:40 PM
Subject: passing a list as a variable



Is there a way to make my commented 'foreach" line act the same as the
line above it?

Can I pass a list as a variable as I am trying to do, or doesn't perl
support that?

###
#!/usr/bin/perl -w
$|=1;
#use strict;

system "clear";
my @array = 1024;
my $list4 = "0..10,33..43,100..111";

   foreach (0..10,33..43,100..111){
   #foreach ($list4){

   $array[$_] = $_;

   print "array--$array[$_]-- --$_--\n";

}
###


Just another way to do it using Set::IntSpan   :-)


#!/usr/bin/perl
use strict;
use warnings;
use Set::IntSpan;

my @array;
my $list4 = "0-10,33-43,100-111";
my $set = Set::IntSpan->new($list4);

foreach ($set->elements()){
$array[$_] = $_;
   print "array--$array[$_]-- --$_--\n";

}


In addition, I'm not sure you would want to create a sparse array like this 
(with undefined elements between the number runs).  But not seeing the 
overall picture of what you want to accomplish makes it difficult to see a 
better solution.


Chris 




--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: String or numbers in AoA?

2006-08-20 Thread Chris Charley


- Original Message - 
From: "chen li" <[EMAIL PROTECTED]>

Newsgroups: perl.beginners
To: 
Sent: Sunday, August 20, 2006 2:20 PM
Subject: String or numbers in AoA?



Dear all,

I try to read some records in one file. Each record
consists of several column which are separated by tab
and ends by "\n". What I would like to do is that to
build an array of array so that each record is a
reference to an anonymous array. 


Here is the format in the file:
1 2 3
1 2 3

I would like to get this output:

@AoA=(
   [1,2,3],
   [1,2,3],
   )

or

$VAR1 = [
 1,
 2,
 3,
   ];
$VAR2 = [
1,
2,
3,
   ];

But when I use Data::Dumper to check the result I get
the following output, which are not what I want.

$VAR1 = [
 '12   3'
   ];
$VAR2 = [
 '12   3'
   ];


Any comments will be appreciated.

Li 


code

#!c:/Perl/bin/perl.exe

use warnings;
use strict;

use Data::Dumper;

my $file_name="data.txt";
open (FH,$file_name) or die " cant' open
$file_name$!";

my @AoA;

while (my $line=) {

chomp $line;

my @temp=split(/t/, $line);




my @temp=split(/\t/, $line);
  ^





push @AoA, [EMAIL PROTECTED];

}
print Data::Dumper->Dump([EMAIL PROTECTED]);


 




__
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com



--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: Parsing HEX Snoop Dump

2006-10-05 Thread Chris Charley


- Original Message - 
From: <[EMAIL PROTECTED]>

Newsgroups: perl.beginners
To: 
Sent: Monday, October 02, 2006 10:33 AM
Subject: Parsing HEX Snoop Dump



I'm trying to parse a huge (~2-5MB) Snoop dump from our servers.
The output is below:

15:44:14.57313 199.117.205.249 -> s31  TCP D=57013 S=4500 Push 
Ack=4051907260 Seq=4004895749 Len=39 Win=49640


  0: 0003 ba0c 272b 000c f860 a0f0 0800 4500'+..ø`E.
 16: 004f 9fe9 4000 3806 0231 c775 cdf9 0a01[EMAIL PROTECTED]
 32: 011f 1194 deb5 eeb5 dc05 f183 32bc 50182.P.
 48: c1e8 78f7  e225 c704 050c 1915 e81d..x%
 64: e91b cf01 01d1 0201 01f2 12c0 0231 30c1.10.
 80: 0101 c209 0401 210a 0656 1187 42   ..!..V..B

15:44:14.66459  s31 -> 199.117.205.249 TCP D=4500 S=57013 
Ack=4004895788 Seq=4051907260 Len=0 Win=64140


  0:  5e00 01c9 0003 ba0c 272b 0800 4500..^...'+..E.
 16: 0028 7e4d 4000 4006 1bf4 0a01 011f c775.([EMAIL 
PROTECTED]@u
 32: cdf9 deb5 1194 f183 32bc eeb5 dc2c 5010.ù..2,P.
 48: fa8c a0a9  ú.

15:44:14.74595  s31 -> 199.117.205.249 TCP D=4500 S=57013 Push 
Ack=4004895788 Seq=4051907260 Len=81 Win=64140


  0:  5e00 01c9 0003 ba0c 272b 0800 4500..^...'+..E.
 16: 0079 7e4e 4000 4006 1ba2 0a01 011f c775[EMAIL 
PROTECTED]@u
 32: cdf9 deb5 1194 f183 32bc eeb5 dc2c 5018.ù..2,P.
 48: fa8c a0fa  e44f c704 050c 1915 e847...O...G
 64: ea45 cf01 01f2 40c0 0101 e117 c006 0609[EMAIL PROTECTED]
 80: 1d08 a4e2 c10a 0301 34f5 a0c4 1a9e 4...
 96: c201 00c2 0902 0021 0a06 2651 9079 c309...!..&Q.y..
112: 0401 210a 9990 0932 91c6 0c00 0121 0f13..!2.!..
128: 0601 1095 1697 f4  ...


What I'd like to see is the time stamp the request came in and time stamp 
the server responded.

Like...

Time:  Transaction Transaction_ID Transaction_Type

15:44:14.57313 199.117.205.249 -> s31   c704 050c (from line 48) Request
15:44:14.74595 s31 -> 199.117.205.249   c704 050c (from line 48) Response

Any ideas?  Anyone have done this before?
TIA


This raises a number of questions. :-)

What constitutes a valid Request/Response? A 'Push Ack' vs. just a 'Push' in 
the first line?

Or is a valid Req/Resp indicated by a 'full' line beginning with 48?

Is it possible for another request to come before a valid Response to the 
first Request?


Chris 




--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: saving surrounding text in substitution

2006-10-10 Thread Chris Charley


- Original Message - 
From: "Kathryn Bushley" <[EMAIL PROTECTED]>

Newsgroups: perl.beginners
To: 
Sent: Tuesday, October 10, 2006 3:17 PM
Subject: saving surrounding text in substitution



Hi,

I've written the following script to substitute names
for codes into a phylogenetic tree (newick format-file
attached) using a global hash with codes as key and
names as values...it seems to be working up to the
second to last line where I make the substitution...I
am able to make the substitution but cannot seem to
save the surrounding text...I've tried $1 and $2 but
in this case no substitution at all happens...any
suggestions or is there an easier to do this?

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

use Bio::Seq;
use Bio::SeqIO;

#initialize id and fasta files
my $codefile = $ARGV[0];
my $treefile = $ARGV[1];

#open alignment list and create a global hash of tree
codes with species name as
#open gi id file and assign file handle
open(ID,$codefile)|| die "can't open id file: $!\n";
#initialize hash
my(@ID);
my %id_global;
my $id;
while (){
 #split on spaces
 my @ID = split(/\s+/);
 #print "ID->".$ID[0]."<-\n"."Code->".$ID[1]."<-\n";
 #get rid of carriage returns
 chomp;
 #define id as the code number
 my $id = $ID[1];
 #print "ID->".$id."<-\n";
 #create a global hash with code number as key and
species name as value
 $id_global{$id}= $ID[0];
 #print $id."VALUE->".$id_global{$id}."<-\n";
}


#test that keys loaded to global hash with correct
value
#foreach my $key (keys %id_global){
#print
"KEY->".$key."<-->VALUE->".$id_global{$key}."<-\n";
#}


#open treefile and while through it, substituting
species name (value) when key(code) found in file.
open (TREE,$treefile)|| die "can't open tree file:
$\n";
#my @TREE;
my $line;
while (){
  foreach my $code (keys %id_global){
  #print
"CODE->".$code."<-VALUE->".$id_global{$code}."\n";
  #initialize line as $_
  $line = $_;

#if ($line =~ m/(.*).$code.(.*)/) {print "MATCH"."
".$code."VALUE->".$id_global{$code}."<-\n";}

  #else {print "NO MATCH"." ".$code."<-\n";}
  $line =~
s/(.*).$code.(.*)/$1.$id_global{$code}.$2/;


Hello Kathryn

As Tom noted in his reply, its probably not necessary to capture $1 and $2.
Just s/$code/$id_global{$code}/ should do it.
I am assuming that the periods you had in there were for concatenation.
If so, they are not necessary. (On the other hand, if you wanted the periods
then you would need to backslash them, s/\.$code\./.$id_global{$code}./ ).

(I've re-writteen your entire code below.You how much simpler it could be.)

  print $line;
  }
}




kathryn


#!/usr/bin/perl
use strict;
use warnings;
use Bio::Seq;
use Bio::SeqIO;

#initialize id and fasta files
my $codefile = $ARGV[0];
my $treefile = $ARGV[1];

#open alignment list and create a global hash of tree codes with species 
name as

#open gi id file and assign file handle
open(ID,$codefile)|| die "can't open id file: $!\n";

my %id_global;

while (){
 my ($id, $code, undef) = split ' ', $_, 3;
 $id_global{$code} = $id;
}

#open treefile and while through it, substituting species name (value) when 
key(code) found in file.

open (TREE,$treefile)|| die "can't open tree file: $\n";

my $line;
while (){
  s/$code/$id_global{$code}/ && print;
}

Chris 




--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: saving surrounding text in substitution

2006-10-10 Thread Chris Charley


- Original Message - 
From: ""John W. Krahn"" <[EMAIL PROTECTED]>

Newsgroups: perl.beginners
To: "Perl Beginners" 
Sent: Tuesday, October 10, 2006 4:43 PM
Subject: Re: saving surrounding text in substitution



Chris Charley wrote:


(I've re-writteen your entire code below.You how much simpler it could 
be.)


#!/usr/bin/perl
use strict;
use warnings;
use Bio::Seq;
use Bio::SeqIO;

#initialize id and fasta files
my $codefile = $ARGV[0];
my $treefile = $ARGV[1];

#open alignment list and create a global hash of tree codes with species
name as
#open gi id file and assign file handle
open(ID,$codefile)|| die "can't open id file: $!\n";

my %id_global;

while (){
 my ($id, $code, undef) = split ' ', $_, 3;


If you want simpler then:

 my ($id, $code) = split;


Yes indeed. In addition, I mucked up the last while loop.
Left my thinking cap in the garage :-(

while (){
   foreach my $code (keys %id_global){
 s/$code/$id_global{$code}/;
  }
  print;
}





 $id_global{$code} = $id;
}



:-)

John
--
Perl isn't a toolbox, but a small machine shop where you can special-order
certain sorts of tools at low cost and in short order.   -- Larry Wall 




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




Re: count the characters between the matches

2006-10-23 Thread Chris Charley


- Original Message - 
From: ""zhihua li"" <[EMAIL PROTECTED]>

Newsgroups: perl.beginners
To: 
Sent: Monday, October 23, 2006 9:05 PM
Subject: count the characters between the matches



hi netters,

I'm curious if there's any smart code to calculate the "distance" between 
the matches in a text.
Suppose I have a text like this: 
syhk...yes...uhg;ka=...yes...yiealg.yes...ghe;a...yes...
Apparently it has multiple words of "yes". I'd like to know how many 
characters there are between the first and the last "yes". The way I now 
come up with to do this is to use substitution to "mark" the first and the 
last match, then use a counting loop to calculate the 
characters..rather straightforward and stupid method.


Anyone has a better idea about that?

Thanks a lot!


This will give the result you want.

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


$_ = 'syhk...yes...uhg;ka=...yes...yiealg.yes...ghe;a...yes...';

if (/.*?(yes).*(yes)/) {
print "position at end of first yes is $+[1]\n";
print "position at beginning of last yes is $-[2]\n";
print "number of characters between first and last is ", $-[2] - 
($+[1] -1 );

}

**prints

position at end of first yes is 10
position at beginning of last yes is 58
number of characters between first and last is 49


Chris 




--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: run script on multiple files

2006-12-23 Thread Chris Charley


- Original Message - 
From: "Kirk Wythers" <[EMAIL PROTECTED]>

Newsgroups: perl.beginners
To: "John W. Krahn" <[EMAIL PROTECTED]>
Cc: "Perl Beginners" 
Sent: Saturday, December 23, 2006 1:32 PM
Subject: Re: run script on multiple files



Thanks or the reply John. I have a couple of questions inline.

On Dec 22, 2006, at 10:53 PM, John W. Krahn wrote:



#! /usr/bin/perl -w
use strict;
use Date::Calc qw(Day_of_Year);
use DBI;

#MICIS climate data munger. Required input argument is the file to
process.
#Use > to redirect output to new file.

#Set the item delimiter to tabs instead of the default commas and  the 
line


The Output Field Separator ($,) has the default value of undef.


I guess I'm too new at this. I don't understand your point.


Above, you said 'Set the item delimiter to tabs instead of the default 
commas'

and John is saying that the default of $, is undef, not a comma.


[snip]


#Part 1. Loop through the 11 header lines to identify the station id.
#The 7th line contains the station ID, and has the format of
#STATION: SOME_STATION, STATE   (Station ID: ##)

for(my $i=1;$i<=6;$i++) {


Your comment says eleven lines but your code says six?


A mistake on my part not updating the comments. The earlier file  format 
had 11 lines.


You need to correct this in John's code where it says:
if (1..11)
should then be
if (1..6)

[snip]

You are using the <> operator to read from the file(s) so this  *will* 
read all
the lines from all the files listed on the command line.  The only 
problem is
that you will not distinguish the headers from the second and  subsequent 
files

listed on the command line.


That will not do. I need to start fresh on each file. Just as if I  ran 
the program as:


./program.pl file1
./program.pl file2
./program.pl file3
ect


And thats what John's solution does. In his code:

  # At eof close the input filehandle to reset $.
   if ( eof ) {
   close ARGV;
   next;
   }

That 'resets' $. to 1 (beginning line of the next file) and the 'next' 
keyword
instructs your program to 'goto' the while (<>) statement above thus not 
processing

any of the statements below it at  the end of each file.


[snip]


This may work better for you:

#!/usr/bin/perl -w
use strict;
use Date::Calc qw(Day_of_Year);
use DBI;


my $dbh = DBI->connect( 'DBI:Pg:dbname=met_data;host=localhost', 
'pguser',

'pguser' )
or die "Couldn't connect to PostgreSQL: $DBI::errstr ($DBI::err) \n";

my $sth = $dbh->prepare( 'INSERT INTO weather (station_id, year,   month, 
day,

doy, date, precip, tmin, tmax, snowfall, snowdepth,  tmean) VALUES
(?,?,?,?,?,?,?,?,?,?,?,?)' );


my $station_id = '';

while ( <> ) {

# Part 1. Loop through the 11 header lines to identify the  station 
id.

# The station ID has the format of:
# STATION: SOME_STATION, STATE   (Station ID: ##)
if ( 1 .. 11 ) {
$station_id = $1 if /\(Station ID:\s*(\S+)\)/;


Thi regular expression wants to match:
\(- a literal left parenthesis
   Station ID:  - then this text
   \s*   - 0 or more spaces
   (\S+)   -  1 or more non-space characters (enclosed in capturing 
parentheses

  whose value will be held in $1)
   \)  -  a final literal right parenthesis




It seems that this is more flexable. ie not dependent upon a certine 
number of header lines. Can you translate the f /\(Station ID:\s*(\S+) 
\)/; part though?



next;
}

# At eof close the input filehandle to reset $.
if ( eof ) {
close ARGV;
next;
}



I think this is suppose to allow the script to jump to the next file. 
Right?


Right


However, this script also reads the first file into the database,  then 
stops.


Don't know why - maybe someone else could say.


Hope this is helpful


Chris



--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: inplace editing

2005-03-16 Thread Chris Charley
- Original Message - 
From: "Hendrik Maryns" <[EMAIL PROTECTED]>
Newsgroups: perl.beginners
To: 
Sent: Wednesday, March 16, 2005 5:35 PM
Subject: inplace editing


Hi,
some time ago I asked for some help to eliminate certain lines from a 
file.  Someone suggested a solution with
{ local ( $^I, @ARGV ) = ( '', <*.log> );
For unix systems, I think you can do inplace editing w/out specifying an 
extension for a backup file, (and thus no backup is created). On a Windows 
machine, this is not the case. The line above would need to be be something 
like:

   { local ( $^I, @ARGV ) = ( '.bak', <*.log> );
Here, it would create a backup file of the original with the extension .bak.
now when I run this I get the error "Can't do inplace edit without backup 
at lexmorf_ruisweg2.pl line 12."

So I'm not sure that I understand what $^I does (I read about the -i 
switch), and I'm rather sure I don't understand what assigning <*.log> to 
@ARGV does.  If I get it right, the <> later on reads from <*.log>, but 
don't I have to open the files in some way first?
$^I does in a script what -i does on the command line. It tells perl that 
you are going to do inplace editing with some extension added as a suffix to 
your original file. <*.log> is the glob operator, and, in this instance, 
finds all files in the current working directory with an extension of .log 
and assigns them to @ARGV (so that when using the angle input operator in 
the while loop, it will get its files to edit from @ARGV). <> later on does 
not read from <*.log>, but from @ARGV.

Here's my code so far:
#! C:\Program Files\Perl\bin perl
use strict;
use warnings;
{ local ( $^I, @ARGV ) = ( '', <*.log> );
while ( <> ) {
s{\[\d+/\d+/\d+\s\d+:\d+\]\s}{}; #remove timestamp
next unless /^<.*>|^\*/; #remove information line
next if /^<.*>\s!/; #remove bot commands
s/\*(.*)\s/<$1> / if /^\*/;  #replace *nick with 
print;
}
}
__END__
The log files contain data of the following form:
[23/02/2005 19:20] =-= SnoopyD is now known as SnoopyDke
[23/02/2005 19:21]  in zen vel zekers als ze hem ni gestroopt 
hemme :p
[23/02/2005 19:21]  ej ma hebde da geleze van diene man die zijn 
ma zo had gestroopt ?
[23/02/2005 19:21]  en dan zo met da vel over hem rond liep ?
[23/02/2005 19:21]  i
[23/02/2005 19:21]  :p
[23/02/2005 19:22] -->| nutty ([EMAIL PROTECTED]) has 
joined #chat2chat
[23/02/2005 19:23] -->| magali ([EMAIL PROTECTED]) has 
joined #chat2chat
[23/02/2005 19:23]  eh SnoopyDke :p
[23/02/2005 19:23]  hebde da geleze
[23/02/2005 19:23]  :p
[23/02/2005 19:23]  !sex Pietje
[23/02/2005 19:23]  lieveke- sleurt Pietje eens mee de bosjes in 
om er donder en bliksem mee te maken...*rr*

Thanks for any help, H.
--
Hendrik Maryns
Interesting websites:
www.lieverleven.be (I cooperate)
www.eu04.com European Referendum Campaign
aouw.org The Art Of Urban Warfare

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 



Re: Determining standard perl modules

2005-03-17 Thread Chris Charley
- Original Message - 
From: "Gavin Henry" <[EMAIL PROTECTED]>
Newsgroups: perl.beginners
To: 
Sent: Thursday, March 17, 2005 4:05 AM
Subject: Determining standard perl modules


Dear all,
How/where do I find out the standard bundled perl modules
Hello Gavin,
perldoc perlmodlib
and then scroll to Standard Modules
Chris
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 



Re: Match filename and attach

2005-04-08 Thread Chris Charley
I think a hash is what I need to be doing but I'm not sure how to load the
keys and the values.  I'm sure I want the keys to be the files in the 
.html
directory and the values to be the item numbers in all the .txt files. 
This
way I can create the hash to function as a table lookup..  Right?

Could someone pls point me in the right direction
TIA!
Brian Volk
Hello Brian
I see many questions in your problem before even attempting to code.
1.Your names in the text files are duplicated in the sample data you 
provided. I'm sure you don't want to send the same web page more than once, 
right?
2.Are all the .html files names, (2000+), included in the text files? In 
other words, will you be sending
out all the .htm files?
3.Your code shows all the pages going to the same recipient. Is this 
correct?

In addition, there are many problems with your code - it won't compile as 
is. So before reviewing the code, it would be helpful to know exactly what 
you want to accomplish.

Chris 


--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 



Re: Copy and rename files

2005-04-20 Thread Chris Charley
- Original Message - 
From: "Brian Milbrandt" <[EMAIL PROTECTED]>
Newsgroups: perl.beginners
To: 
Sent: Tuesday, April 19, 2005 6:22 PM
Subject: Copy and rename files

I am trying to convert a unix script to perl.  The script takes 2 command 
line arguments, source and target.  I am unable to get the file copy and 
rename function working properly.  Here is what I have that is not working 
properly.

$target is the target directory variable
$source is the source directory variable
opendir DH, "/$target";
foreach $file (readdir DH)
{ printf " the file name is %s\n", $file;
next unless $file =~ \/.abc$/ and !-z $name;
 my $newfile = /$target//$file;
 $newfile =~ s/\.abc$/.xyz/;
 $filecount += 1;
}
Hello Brian,
I did what you wanted to do on my computer, (Windows XP). The code is pasted 
below, followed by some explanations. You should be able to get the same 
results by plugging in abc and xyz where I had html and txt. Also, with 
source and target directories of your choosing.

Chris
#!/usr/bin/perl
use strict; # Always declare this and warnings so perl can catch and 
report errors
use warnings;
use File::Copy;

my $source = "/Run";
my $target = "/temp";
my $filecount;
opendir DH, $source or die "Unable to open directory $source: $!;
for (readdir DH) {
   next unless /html?$/ && -s;# next unless 'html', (or abc), and 
non-zero file size
   print "The fileneme is $_\n";
   (my $txt = $_) =~ s/html?$/txt/;# Change file extension to txt, (or 
xyz). Changed name now in $txt.
   copy("$source/$_", "$target/$txt");
   $filecount++;
}
close DH;

print "$filecount files copied\n";

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 



Re: Copy and rename files

2005-04-20 Thread Chris Charley
A correction to the code for 1 line below  :-(
Chris
Hello Brian,
I did what you wanted to do on my computer, (Windows XP). The code is 
pasted below, followed by some explanations. You should be able to get the 
same results by plugging in abc and xyz where I had html and txt. Also, 
with source and target directories of your choosing.

#!/usr/bin/perl
use strict; use warnings;
use File::Copy;
my $source = "/Run";
my $target = "/temp";
my $filecount;
opendir DH, $source or die "Unable to open directory $source: $!;
for (readdir DH) {
   next unless /html?$/ && -s;
 next unless /html?$/ && -s "$source/$_";
   print "The fileneme is $_\n";
   (my $txt = $_) =~ s/html?$/txt/;  copy("$source/$_", "$target/$txt");
   $filecount++;
}
close DH;
print "$filecount files copied\n";


--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 



Cannot get CPAN module working - cannot install

2005-05-03 Thread Chris Charley
Hope someone may know how to fix this,  :-)
(The cpan run is pasted in below)
cpan> force install List::PowerSet
Running install for module List::PowerSet
Running make for N/NI/NIKC/List-PowerSet-0.01.tar.gz
Checksum for \.cpan\sources\authors\id\N\NI\NIKC\List-PowerSet-0.01.tar.gz 
ok
List-PowerSet-0.01/
List-PowerSet-0.01/MANIFEST
List-PowerSet-0.01/t/
List-PowerSet-0.01/t/pod.t
List-PowerSet-0.01/t/01basic.t
List-PowerSet-0.01/META.yml
List-PowerSet-0.01/MANIFEST.SKIP
List-PowerSet-0.01/lib/
List-PowerSet-0.01/lib/List/
List-PowerSet-0.01/lib/List/PowerSet.pm
List-PowerSet-0.01/Makefile.PL
List-PowerSet-0.01/Build.PL
Removing previously used \.cpan\build\List-PowerSet-0.01

 CPAN.pm: Going to build N/NI/NIKC/List-PowerSet-0.01.tar.gz
Checking if your kit is complete...
Looks good
Writing Makefile for List::PowerSet
   -- OK
Running make test
'test' is not recognized as an internal or external command,
operable program or batch file.
  test -- NOT OK
Running make install
'install' is not recognized as an internal or external command,
operable program or batch file.
  install  -- NOT OK
cpan>
I am running Win XP with Active State. In my \Perl\bin directory, make is 
there and so is nmake.err. I don't know why I am getting the messages saying 
test and install are not recognized, (above).

Thanks in advance for any help offered.
Chris

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 



Re: sorting a hash

2005-05-09 Thread Chris Charley
Hi Teddy
This works :-)
for (sort byname keys %$ref) {
print "$_ has the name $ref->{$_}{name} and has $ref->{$_}{age} years\n";
}
sub byname {
{$ref->{$a}{name} cmp $ref->{$b}{name}}
}
Chris
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 



Re: sorting a hash

2005-05-09 Thread Chris Charley
- Original Message - 
From: <[EMAIL PROTECTED]>
Newsgroups: perl.beginners
To: "Octavian Rasnita" <[EMAIL PROTECTED]>; 
Sent: Monday, May 09, 2005 4:30 PM
Subject: Re: sorting a hash


- Original Message - 
From: "Octavian Rasnita" <[EMAIL PROTECTED]>
To: 
Sent: Monday, May 09, 2005 2:32 PM
Subject: sorting a hash


Hi,
I have a reference to a hash of hashes, something like:
[snip]
I want to sort the persons with the codes 'a', 'b', and 'c' by  their 
name,
 
and print something like:
"a has the name z and has 14 years".
... then the next person in  order...
foreach my $key (sort (keys %$ref)){
print "$key => $ref->{$key}{name} is $ref->{$key}{age}\n";
}
Unless I'm in error, the requirement was to sort the results in order by 
name, not by the key  :-)


--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 



Re: Two Dimensional Array Problem

2005-06-03 Thread Chris Charley

[snip]

Hi Brian,


I usually deal with multidimensional arrays this way:

$i = 0;
while (@results = $sth->fetchrow_array ())
{
   $x = $results[0];
   $y = $results[1];
   @points = ($x, $y);
   $data[$i] = [EMAIL PROTECTED];
   $i++;
}


Just a note about a possible problem with the statement:
$data[$i] = [EMAIL PROTECTED];

Everytime through this loop, the reference to @points, ([EMAIL PROTECTED]), is 
assigned to @data. But this is the same address. The result is that all the 
array refs assigned to @data are the same. So, the *last* assignment to 
@points, (x,y), will be the values for every element of @data.


A correct way to say it in your example would be:
$data[$i] = [EMAIL PROTECTED];

Another would be to declare my @points in the loop, so that you have a fresh 
ref every time through the loop. Then you could say:

$data[$i] = [EMAIL PROTECTED];

Chris 




--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: Append to hash

2005-07-15 Thread Chris Charley


Jakob Kofoed wrote:


I have a file with some navigation (x and y's) and needed to fill in
point between exiting points.

My in put file:
60  6174210
600017  6174213
600028  6174206
600035  6174216
600045  6174209

For calculation I need to use line 1 and 2 for calculating one point
and then line 2 and 3 and so on ...
I solved it by using Xaviers tip on Tie::File:

use Tie::File;
tie my @line, 'Tie::File', $ARGV[0] or die "could not open $ARGV[0]: $!";
my $cnt1 = 0;
my $cnt2 = 0;
while ( $cnt1 < $ARGV[1] ) {
   $cnt2++;
   #print " $cnt1 $cnt2\n";
   my @rec1 = split(' ', $line[$cnt1]);
   my @rec2 = split(' ', $line[$cnt2]);
   my $newin = (($rec1[0] - $rec2[0]) / 2) + $rec2[0];
   my $newxl = (($rec1[1] - $rec2[1]) / 2) + $rec2[1];
   print "@rec1\n";
   print "$newin $newxl\n";
   $cnt1 = $cnt2;
}



This code will not print the very last line of the file. You need to add the
line (below) after  you exit the while loop.

print "@rec2\n";



where $ARGV[1] is the number of lines in the file.


How do you know beforehand the number of lines in the file?

By the way, I think that the test in the while loop should be:

while ( $cnt1 < $ARGV[1] - 1 ) {



Could I have used an array as you mentioned in the bottom of your comment?



Yes, you could have (and not needed both: Tie::File and $ARGV[1]). The code 
below

reads the file in $ARGV[0] into @line

my @line = <>;

while ($cnt1 < $#line) {
   etc.


As a last note, I wouldn't have read the whole file into an array (which is
often called 'slurping' a file) and wouldn't have needed to keep the 2 count
variables. Instead, I used $first and $second to capture the needed lines.
This way, if you are dealing with a very large file, you only read 1 line at
a time into memory instead of 'slurping' the entire file into an array. But
the method you chose should work as well (if not a huge file).  :-)


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

my $first;
my $second;

while (<>) {
   chomp;
   $first = $_, next unless $first;
   $second = $_;
   my @rec1 = split ' ', $first;
   my @rec2 = split ' ', $second;
   my $newin = (($rec1[0] - $rec2[0]) / 2) + $rec2[0];
   my $newxl = (($rec1[1] - $rec2[1]) / 2) + $rec2[1];
   print "$first\n";
   print "$newin  $newxl\n";
   $first = $second;
}
print "$second\n";

Chris



--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: Remembering Positions in Array after processing the element

2005-07-31 Thread Chris Charley


- Original Message - 
From: "John W. Krahn" <[EMAIL PROTECTED]>

Newsgroups: perl.beginners
To: "Perl Beginners" 
Sent: Friday, July 29, 2005 10:35 PM
Subject: Re: Remembering Positions in Array after processing the element



Edward WIJAYA wrote:

Hi,


Hello,


I wanted to append two subsequent characters (non *) in
an array and then storing them into new array.
But then I also want to restore the '*' string in its
initial position in the new array result.


Perhaps this will give you some ideas:


perl -le'

@x = qw( A B C * D );
print @x . "  @x";
for ( reverse 0 .. $#x ) {
   push @y, [ $_, splice @x, $_, 1, () ] if $x[ $_ ] =~ /[^A-Z]/;
   }


   splice @x, $_, 1, ()
   Are the empty parens needed here? Seemed to work ok for me without them.


print @x . "  @x";
@x = map "X$_", @x;
print @x . "  @x";
for ( @y ) {


   for ( reverse @y )
   Need to restore the 'special' characters beginning from the beginning
   of the array - (can see the error your way with data set [A * B * C]).
   The chars and their positions were stored in the @y array in reverse 
order. :-)




   splice @x, $_->[0], 0, $_->[1];
   }
print @x . "  @x";
'
5  A B C * D
4  A B C D
4  XA XB XC XD
5  XA XB XC * XD



John
--
use Perl;
program
fulfillment


Hi John
I wanted to try to make up a function like Edward wanted and used your 
solution

and 'added' to it.

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

my @x = qw( A * B * C);
print "@{[get_array(@x)]}";

sub get_array{
my @x = @_;
my @y;

for ( reverse 0 .. $#x ) {
push @y, [ $_, splice @x, $_, 1, () ] if $x[ $_ ] =~ /[^A-Z]/;
   }

my @i = @x[1..$#x];
my @j = @x[0..$#x-1];
@x = map "$i[$_]$j[$_]", 0..$#i;
if ($x[0]) {
 unshift @x, $x[0];
}
else {
 local $" = ", ";
 die "died: fed bad array, [ @_ ] $!";
}

for ( reverse @y ) {
splice @x, $_->[0], 0, $_->[1];
   }
   return @x;
}

Chris 




--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: Remembering Positions in Array after processing the element

2005-07-31 Thread Chris Charley

Hello John

I don't feel very comfortable with some of the code I listed.  I thought 
that using @i and @j was a way to avoid warnings (as originally proposed by 
Edward W.) when the array argument had bad data, but the same situation 
occurs even with my solution. I guess the question is how would one want to 
handle bad data - or even if it was likely that no bad data would ever be a 
possibility. Also, could there be more than one "*" in the array. These 
questions would need to be answered before one could make a final 
determination on how to procede.  :-(


Thanks for the tip on using unshift.

Chris 




--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: strftime Problem

2005-08-09 Thread Chris Charley

Hi Dave

I can get it to work if I do not include use Time::localtime.
Wonder why it worked for you in the first instance?

Chris


--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: converting to FLOATING_POINT..

2005-08-17 Thread Chris Charley

Vineet Pande wrote:


Thanks Rex:
Please help me in knowing one more related thing. I have from this script 
of mine an output like this:

0.00.00
0.460.37
0.8106.29
1.2140.56
1.6168.75
2.0186.37
2.4207.82
2.8225.45
3.2235.88
3.6245.55
4.0250.61
4.4260.06
4.8264.60
5.2271.11
5.6272.90
6.0275.62
6.4283.33
6.8283.55
7.2284.58
7.6285.22
8.0287.51
8.4290.38
8.8294.09
9.2297.01
9.6296.16
10.0291.57
10.4292.88
10.8297.28
11.2301.13

I want to see it formatted more beautifully, i.e. decimals under decimals. 
How do we get that. My script is:


use strict;
use warnings;

my $mdout_file = "mdout.txt";

my $mdout_xtemp_file = "temp.txt";


open IN, $mdout_file or die;
open OUT, ">$mdout_xtemp_file" or die;


while ()

  {

  if ($_ =~ ( /TEMP/ ))

{

my $time = (substr($_, 30, 14));
$time =~ s/\s//g;
my $temp = (substr($_, 53, 10));
$temp =~ s/\s//g;

 $time = sprintf("%0.1f", ($time * 2));


foreach ($time)
  {
print OUT $time ;
print OUT "";
foreach ($temp) {
   print OUT $temp;
   print OUT "\n";
}
  }

}

  }



Hi Vineet

You could format *pretty* by using sprintf() instead of print. I would do it 
like below.


use strict;
use warnings;

my $mdout_file = "mdout.txt";

my $mdout_xtemp_file = "temp.txt";


open IN, $mdout_file or die;
open OUT, ">$mdout_xtemp_file" or die;


while (){

  if (/TEMP/) {

  my $time = (substr($_, 30, 14));
  $time =~ s/\s//g;
  my $temp = (substr($_, 53, 10));
  $temp =~ s/\s//g;

  print OUT sprintf("%4.1f %6.2f\n", $time*2, $temp);
  }
}

__END__

You should see the documentation;perldoc -f sprintf
and this will help you understand the sprintf function better.

Also, I took out the foreach loops in your print routine. They really do 
nothing useful!


Rex was mistaken in saying a minus, '-', would right align. It left aligns 
:-)


HTH
Chris




--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: converting to FLOATING_POINT..

2005-08-17 Thread Chris Charley

[...]


Hi Vineet

You could format *pretty* by using sprintf() instead of print. I would do 
it like below.


use strict;
use warnings;

my $mdout_file = "mdout.txt";

my $mdout_xtemp_file = "temp.txt";


open IN, $mdout_file or die;
open OUT, ">$mdout_xtemp_file" or die;


while (){

  if (/TEMP/) {

  my $time = (substr($_, 30, 14));
  $time =~ s/\s//g;
  my $temp = (substr($_, 53, 10));
  $temp =~ s/\s//g;

  print OUT sprintf("%4.1f %6.2f\n", $time*2, $temp);
  }
}



The solution above *assumes* that you would know beforehand the widths you 
want for each column (determined by the largest number in each column you 
want to format).


The solution below allows you to determine the greatest width required 
programmatically using the max() function from the List::Util module. Then, 
the max widths for each column are used in the sprintf function, (which uses 
a '*' as a placeholder, if thats an accurate term for the asterisk  :-)  ). 
This would provide a better solution (in place of 'hard coding' the widths 
in sprintf).



#!/usr/bin/perl
use strict;
use warnings;
use List::Util qw/ max /;

my $mdout_file = "mdout.txt";

my $mdout_xtemp_file = "temp.txt";


open IN, $mdout_file or die;

my @time;
my @temp;
while (){

  if (/TEMP/) {

  my $time = (substr($_, 30, 14));
  $time =~ s/\s//g;
  my $temp = (substr($_, 53, 10));
  $temp =~ s/\s//g;

  push @time, $time*2;
  push @temp, $temp;
  }
}
close IN or die $!;

my $maxlen_time = max map{ length } @time;
my $maxlen_temp = max map{ length } @temp;

open OUT, ">$mdout_xtemp_file" or die;

for my $i (0..$#time) {
print OUT sprintf("%*.1f %*.2f\n",
 $maxlen_time, $time[$i], $maxlen_temp, $temp[$i]);
}
close OUT or die $!;


Chris



--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




  1   2   >