Re: insert in perl tk

2012-08-24 Thread Irfan Sayed
i have to call localtime () function to get the latest time everytime when i 
print the lines using insert method
i mean , i need to print the latest time in scrolled text box

lets say :

use Tk;
$mw = MainWindow-new();
my $t = $mw-Scrolled(Text)-pack (-side = 'left', -expand=1);
$t-insert(end, $c = \gettime);

sub gettime 
{
 $c = localtime();
return $c;
}

so whenever i call insert method , it shud call function gettime and print the 
latest time in the text box 
please suggest

regards
irfan






 From: Jim Gibson jimsgib...@gmail.com
To: Perl Beginners beginners@perl.org 
Sent: Friday, August 24, 2012 11:13 AM
Subject: Re: insert in perl tk
 

On Aug 23, 2012, at 9:35 PM, Irfan Sayed wrote:

 thanks. this will help to print the contents of array on separate line.
 however, if at all we need to call function then what is the syntax, how we 
 can call that ?

What function do you want to call? When do you want to call it? What does the 
function have to do with the array you want to print? What does it have to do 
with Tk?

 
 please suggest .

Please let us know in more detail what you are trying to do.

Thanks.


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

Re: insert in perl tk

2012-08-24 Thread Shekar
Try this.

$t-insert(end, gettime);


--
Shekar


On Fri, Aug 24, 2012 at 11:58 AM, Irfan Sayed irfan_sayed2...@yahoo.comwrote:

 i have to call localtime () function to get the latest time everytime when
 i print the lines using insert method
 i mean , i need to print the latest time in scrolled text box

 lets say :

 use Tk;
 $mw = MainWindow-new();
 my $t = $mw-Scrolled(Text)-pack (-side = 'left', -expand=1);
 $t-insert(end, $c = \gettime);

 sub gettime
 {
  $c = localtime();
 return $c;
 }

 so whenever i call insert method , it shud call function gettime and print
 the latest time in the text box
 please suggest

 regards
 irfan





 
  From: Jim Gibson jimsgib...@gmail.com
 To: Perl Beginners beginners@perl.org
 Sent: Friday, August 24, 2012 11:13 AM
 Subject: Re: insert in perl tk


 On Aug 23, 2012, at 9:35 PM, Irfan Sayed wrote:

  thanks. this will help to print the contents of array on separate line.
  however, if at all we need to call function then what is the syntax, how
 we can call that ?

 What function do you want to call? When do you want to call it? What does
 the function have to do with the array you want to print? What does it have
 to do with Tk?

 
  please suggest .

 Please let us know in more detail what you are trying to do.

 Thanks.


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



Re: insert in perl tk

2012-08-24 Thread Irfan Sayed
thanks. 
it worked!

regards
irfan


From: Shekar c.shekar1...@gmail.com
To: Irfan Sayed irfan_sayed2...@yahoo.com 
Cc: Jim Gibson jimsgib...@gmail.com; Perl Beginners beginners@perl.org 
Sent: Friday, August 24, 2012 12:23 PM
Subject: Re: insert in perl tk
 

Try this.

$t-insert(end, gettime);


--
Shekar



On Fri, Aug 24, 2012 at 11:58 AM, Irfan Sayed irfan_sayed2...@yahoo.com wrote:

i have to call localtime () function to get the latest time everytime when i 
print the lines using insert method
i mean , i need to print the latest time in scrolled text box

lets say :

use Tk;
$mw = MainWindow-new();
my $t = $mw-Scrolled(Text)-pack (-side = 'left', -expand=1);
$t-insert(end, $c = \gettime);

sub gettime
{
 $c = localtime();
return $c;
}

so whenever i call insert method , it shud call function gettime and print the 
latest time in the text box

please suggest

regards
irfan






 From: Jim Gibson jimsgib...@gmail.com
To: Perl Beginners beginners@perl.org
Sent: Friday, August 24, 2012 11:13 AM

Subject: Re: insert in perl tk



On Aug 23, 2012, at 9:35 PM, Irfan Sayed wrote:

 thanks. this will help to print the contents of array on separate line.
 however, if at all we need to call function then what is the syntax, how we 
 can call that ?

What function do you want to call? When do you want to call it? What does the 
function have to do with the array you want to print? What does it have to do 
with Tk?


 please suggest .

Please let us know in more detail what you are trying to do.

Thanks.


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

Re: insert in perl tk

2012-08-24 Thread Shlomi Fish
Hi Shekar,

On Fri, 24 Aug 2012 12:23:21 +0530
Shekar c.shekar1...@gmail.com wrote:

 Try this.
 
 $t-insert(end, gettime);
 

Please don't recommend people to use leading ampersands in subroutine calls:

* http://perl-begin.org/tutorials/bad-elements/#ampersand-in-subroutine-calls

* https://www.socialtext.net/perl5/subroutines_called_with_the_ampersand

Instead write:

$t-insert(end, gettime());

Regards,

Shlomi Fish

 
 --
 Shekar
 
 
 On Fri, Aug 24, 2012 at 11:58 AM, Irfan Sayed
 irfan_sayed2...@yahoo.comwrote:
 
  i have to call localtime () function to get the latest time
  everytime when i print the lines using insert method
  i mean , i need to print the latest time in scrolled text box
 
  lets say :
 
  use Tk;
  $mw = MainWindow-new();
  my $t = $mw-Scrolled(Text)-pack (-side = 'left', -expand=1);
  $t-insert(end, $c = \gettime);
 
  sub gettime
  {
   $c = localtime();
  return $c;
  }
 
  so whenever i call insert method , it shud call function gettime
  and print the latest time in the text box
  please suggest
 
  regards
  irfan
 
 
 
 
 
  
   From: Jim Gibson jimsgib...@gmail.com
  To: Perl Beginners beginners@perl.org
  Sent: Friday, August 24, 2012 11:13 AM
  Subject: Re: insert in perl tk
 
 
  On Aug 23, 2012, at 9:35 PM, Irfan Sayed wrote:
 
   thanks. this will help to print the contents of array on separate
   line. however, if at all we need to call function then what is
   the syntax, how
  we can call that ?
 
  What function do you want to call? When do you want to call it?
  What does the function have to do with the array you want to print?
  What does it have to do with Tk?
 
  
   please suggest .
 
  Please let us know in more detail what you are trying to do.
 
  Thanks.
 
 
  --
  To unsubscribe, e-mail: beginners-unsubscr...@perl.org
  For additional commands, e-mail: beginners-h...@perl.org
  http://learn.perl.org/
 



-- 
-
Shlomi Fish   http://www.shlomifish.org/
Rethinking CPAN - http://shlom.in/rethinking-cpan

Bill Gates, CEO of Microsoft decides to use Richard Stallman’s Emacs as the
basis of his company’s state‐of‐the‐art product Microsoft Editing Macros™
Enterprise Edition XP .NET Professional.

Please reply to list if it's a mailing list post - http://shlom.in/reply .

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




Re: insert in perl tk

2012-08-24 Thread Shekar
Thanks  for the correction Shlomi.

Mistake from my side, i copy pasted the wrong line from my terminal !!!

--
Shekar


On Fri, Aug 24, 2012 at 2:49 PM, Shlomi Fish shlo...@shlomifish.org wrote:

 Hi Shekar,

 On Fri, 24 Aug 2012 12:23:21 +0530
 Shekar c.shekar1...@gmail.com wrote:

  Try this.
 
  $t-insert(end, gettime);
 

 Please don't recommend people to use leading ampersands in subroutine
 calls:

 *
 http://perl-begin.org/tutorials/bad-elements/#ampersand-in-subroutine-calls

 * https://www.socialtext.net/perl5/subroutines_called_with_the_ampersand

 Instead write:

 $t-insert(end, gettime());

 Regards,

 Shlomi Fish

 
  --
  Shekar
 
 
  On Fri, Aug 24, 2012 at 11:58 AM, Irfan Sayed
  irfan_sayed2...@yahoo.comwrote:
 
   i have to call localtime () function to get the latest time
   everytime when i print the lines using insert method
   i mean , i need to print the latest time in scrolled text box
  
   lets say :
  
   use Tk;
   $mw = MainWindow-new();
   my $t = $mw-Scrolled(Text)-pack (-side = 'left', -expand=1);
   $t-insert(end, $c = \gettime);
  
   sub gettime
   {
$c = localtime();
   return $c;
   }
  
   so whenever i call insert method , it shud call function gettime
   and print the latest time in the text box
   please suggest
  
   regards
   irfan
  
  
  
  
  
   
From: Jim Gibson jimsgib...@gmail.com
   To: Perl Beginners beginners@perl.org
   Sent: Friday, August 24, 2012 11:13 AM
   Subject: Re: insert in perl tk
  
  
   On Aug 23, 2012, at 9:35 PM, Irfan Sayed wrote:
  
thanks. this will help to print the contents of array on separate
line. however, if at all we need to call function then what is
the syntax, how
   we can call that ?
  
   What function do you want to call? When do you want to call it?
   What does the function have to do with the array you want to print?
   What does it have to do with Tk?
  
   
please suggest .
  
   Please let us know in more detail what you are trying to do.
  
   Thanks.
  
  
   --
   To unsubscribe, e-mail: beginners-unsubscr...@perl.org
   For additional commands, e-mail: beginners-h...@perl.org
   http://learn.perl.org/
  



 --
 -
 Shlomi Fish   http://www.shlomifish.org/
 Rethinking CPAN - http://shlom.in/rethinking-cpan

 Bill Gates, CEO of Microsoft decides to use Richard Stallman’s Emacs as the
 basis of his company’s state‐of‐the‐art product Microsoft Editing Macros™
 Enterprise Edition XP .NET Professional.

 Please reply to list if it's a mailing list post - http://shlom.in/reply .



insert in perl tk

2012-08-23 Thread Irfan Sayed
hi,

can we call function in the insert method of perl tk ?
i have code like this:

 $t-insert(end, \abc);

so when this line gets executed, it should first call function abc
please suggest

regards
irfan


Re: insert in perl tk

2012-08-23 Thread Irfan Sayed
can someone please suggest ?

regards
irfan




 From: Irfan Sayed irfan_sayed2...@yahoo.com
To: beginners@perl.org beginners@perl.org 
Sent: Thursday, August 23, 2012 4:15 PM
Subject: insert in perl tk 
 
hi,

can we call function in the insert method of perl tk ?
i have code like this:

 $t-insert(end, \abc);

so when this line gets executed, it should first call function abc
please suggest

regards
irfan

Re: insert in perl tk

2012-08-23 Thread John SJ Anderson
On Thursday, August 23, 2012 at 10:15 AM, Irfan Sayed wrote:
 can someone please suggest ?
 

Explain what you're actually trying to achieve, instead of asking how to do 
what you think will let you accomplish what you're trying to achieve.

Yes, if you write the insert() method properly, you could certainly pass it 
those two arguments and have it call the second one (you don't need to quote 
the function reference, however). BUT I can't think of a good reason why you'd 
want to do that, so you need to explain what you're actually trying to do, 
because what you're asking about looks really silly. 
 
Also, 6.5 hours is not a terribly long time to wait for an answer on this list. 
Please be more patient in the future before sending additional traffic. 

j.




Re: insert in perl tk

2012-08-23 Thread Irfan Sayed
it was quite rude. anyway 
lets say if i have to display the contents of array using insert method.
if i just type :  $t-insert(end, @arr1);
then surely , it will print the contents of array but on the same line 

i need to print the contents of array on separate line , so , i thought , i 
should write one function where i will print the contents of array on each line 
and call that function from insert method
please suggest

regards
irfan




 From: John SJ Anderson geneh...@genehack.org
To: beginners@perl.org beginners@perl.org 
Sent: Thursday, August 23, 2012 10:54 PM
Subject: Re: insert in perl tk
 
On Thursday, August 23, 2012 at 10:15 AM, Irfan Sayed wrote:
 can someone please suggest ?
 

Explain what you're actually trying to achieve, instead of asking how to do 
what you think will let you accomplish what you're trying to achieve.

Yes, if you write the insert() method properly, you could certainly pass it 
those two arguments and have it call the second one (you don't need to quote 
the function reference, however). BUT I can't think of a good reason why you'd 
want to do that, so you need to explain what you're actually trying to do, 
because what you're asking about looks really silly. 

Also, 6.5 hours is not a terribly long time to wait for an answer on this list. 
Please be more patient in the future before sending additional traffic. 

j.

Re: insert in perl tk

2012-08-23 Thread Jim Gibson

On Aug 23, 2012, at 10:51 AM, Irfan Sayed wrote:

 it was quite rude. anyway 

What was quite rude?

 lets say if i have to display the contents of array using insert method.
 if i just type :  $t-insert(end, @arr1);
 then surely , it will print the contents of array but on the same line 

I don't use Perl/Tk, but I am assuming $t is some sort of Tk widget, and you 
are attempting to add a string to the end of it. Maybe you can post a short, 
complete program that demonstrates what you are trying to do.

 
 i need to print the contents of array on separate line , so , i thought , i 
 should write one function where i will print the contents of array on each 
 line and call that function from insert method
 please suggest

I would recommend putting whatever you want to insert into a scalar variable 
and inserting that by making it the second argument of your insert statement. 
For example, if you want to insert the elements of an array, one element per 
line, do this:

my $text = join(\n,@arr1);
$t-insert('end', $text);


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




Re: insert in perl tk

2012-08-23 Thread Shawn H Corey
On Thu, 23 Aug 2012 10:51:09 -0700 (PDT)
Irfan Sayed irfan_sayed2...@yahoo.com wrote:

 i need to print the contents of array on separate line , so , i
 thought , i should write one function where i will print the contents
 of array on each line

Do you mean you want each item from an array on each line? If so:

$t-insert(end, join( \n, @array ));

See `perldoc -f join` for details.


-- 
Just my 0.0002 million dollars worth,
  Shawn

Programming is as much about organization and communication
as it is about coding.

_Perl links_
official site   : http://www.perl.org/
beginners' help : http://learn.perl.org/faq/beginners.html
advance help: http://perlmonks.org/
documentation   : http://perldoc.perl.org/
news: http://perlsphere.net/
repository  : http://www.cpan.org/
blog: http://blogs.perl.org/
regional groups : http://www.pm.org/

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




Re: insert in perl tk

2012-08-23 Thread Irfan Sayed
thanks. this will help to print the contents of array on separate line.
however, if at all we need to call function then what is the syntax, how we can 
call that ?

please suggest .

regards
irfan




 From: Shawn H Corey shawnhco...@gmail.com
To: beginners@perl.org 
Cc: Irfan Sayed irfan_sayed2...@yahoo.com 
Sent: Thursday, August 23, 2012 11:40 PM
Subject: Re: insert in perl tk
 
On Thu, 23 Aug 2012 10:51:09 -0700 (PDT)
Irfan Sayed irfan_sayed2...@yahoo.com wrote:

 i need to print the contents of array on separate line , so , i
 thought , i should write one function where i will print the contents
 of array on each line

Do you mean you want each item from an array on each line? If so:

    $t-insert(end, join( \n, @array ));

See `perldoc -f join` for details.


-- 
Just my 0.0002 million dollars worth,
  Shawn

Programming is as much about organization and communication
as it is about coding.

    _Perl links_
official site   : http://www.perl.org/
beginners' help : http://learn.perl.org/faq/beginners.html
advance help    : http://perlmonks.org/
documentation   : http://perldoc.perl.org/
news            : http://perlsphere.net/
repository      : http://www.cpan.org/
blog            : http://blogs.perl.org/
regional groups : http://www.pm.org/

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

Re: insert in perl tk

2012-08-23 Thread Jim Gibson

On Aug 23, 2012, at 9:35 PM, Irfan Sayed wrote:

 thanks. this will help to print the contents of array on separate line.
 however, if at all we need to call function then what is the syntax, how we 
 can call that ?

What function do you want to call? When do you want to call it? What does the 
function have to do with the array you want to print? What does it have to do 
with Tk?

 
 please suggest .

Please let us know in more detail what you are trying to do.

Thanks.


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




Re: insert

2012-05-08 Thread Uri Guttman

On 05/07/2012 04:47 PM, timothy adigun wrote:


sub get_data {
 my ($file) = @_;
 my $arr_ref = [];
 open my $fh, '', $file or die can't open this file: $!;
 while ($fh) {
 chomp;
 push @$arr_ref, $_;
 }
 close $fh or die can't close file:$!;
 return $arr_ref;
}


why so much code to slurp in an array of lines? this does the while loop:

chomp( my @lines = $fh ) ;
return \@lines ;

no need for the $arr_ref line or even the close line as the handle will 
be closed upon leaving scope.



or better yet use File::Slurp in list mode and it has a chomp option now.

uri


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




insert

2012-05-07 Thread lina
Hi,

I have two files, one with

3
2
1

another is:

3 1
3 2
6 3

How can I insert the first file into the middle of the second file,

Thanks ahead for your suggestions,

Best regards,

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




Re: insert

2012-05-07 Thread Shawn H Corey

On 12-05-07 03:36 AM, lina wrote:

How can I insert the first file into the middle of the second file,


What code have you tried so far and please provide the expected output 
for your example.



--
Just my 0.0002 million dollars worth,
  Shawn

Programming is as much about organization and communication
as it is about coding.

[updated for today's programming]
Show me your code and conceal your interfaces, and I shall continue
to be mystified. Show me your interfaces, and I won't usually need
your code; it'll be obvious.
-- Fred Brooks

CPAN http://www.cpan.org/
The world's largest repository of software;
all of it tested; all of it free.

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




Re: insert

2012-05-07 Thread lina
On Mon, May 7, 2012 at 7:52 PM, Shawn H Corey shawnhco...@gmail.com wrote:
 On 12-05-07 03:36 AM, lina wrote:

 How can I insert the first file into the middle of the second file,


 What code have you tried so far and please provide the expected output for
 your example.


I can only write some preamble, here it what I came so far,

#!/usr/bin/env perl

use strict;
use warnings;
use autodie qw(open close);
use 5.012;

open my $fh1, '', file1;
open my $fh2, '', file2;

my @parts1;

my @parts2;


while($fh2){
@parts2 =  split /\s+/, $_;
}

foreach(@parts2){
#print $_;
}

while($fh1){
#print $_;
@parts1 = split //,$_;
}

print $parts1[0];




$ more file1
3
2
1

$ more file2
1  2
3  4
5  6

**OUTPUT***

1   3   2
3   2   4
5   1   6

Thanks,


 --
 Just my 0.0002 million dollars worth,
  Shawn

 Programming is as much about organization and communication
 as it is about coding.

 [updated for today's programming]
 Show me your code and conceal your interfaces, and I shall continue
 to be mystified. Show me your interfaces, and I won't usually need
 your code; it'll be obvious.
        -- Fred Brooks

 CPAN http://www.cpan.org/
 The world's largest repository of software;
 all of it tested; all of it free.

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



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




Re: insert

2012-05-07 Thread Jim Gibson

On May 7, 2012, at 5:51 AM, lina wrote:

 On Mon, May 7, 2012 at 7:52 PM, Shawn H Corey shawnhco...@gmail.com wrote:
 On 12-05-07 03:36 AM, lina wrote:
 
 How can I insert the first file into the middle of the second file,
 
 
 What code have you tried so far and please provide the expected output for
 your example.
 
 
 I can only write some preamble, here it what I came so far,
 
 #!/usr/bin/env perl
 
 use strict;
 use warnings;
 use autodie qw(open close);
 use 5.012;
 
 open my $fh1, '', file1;
 open my $fh2, '', file2;
 
 my @parts1;
 
 my @parts2;
 
 
 while($fh2){
   @parts2 =  split /\s+/, $_;
 }

This loop continually reassigns the contents of the line read to @parts2. As a 
result, only the data from the last line will be saved.

If you only have one value per line, there is no need to split the line on 
whitespace. Just use chomp to remove the new line from the end, and use push to 
save all of the lines:

while($fh2) {
  chomp;
  push(@parts2,$_);
}

That can be replaced with this:

@parts2 = $fh2;
chomp(@parts2);

 
 while($fh1){
   #print $_;
   @parts1 = split //,$_;
 }

That last line will split the input line into single characters, since the 
empty regular expression will match everywhere. Is that what you want to do?

Also, you are overwriting the entire array each time. Either fix this as for 
@parts2, or print out the array within the loop. Assuming that you want to 
split one whitespace, here is one way to do the latter (untested):

my $i = 0;
while($fh1) {
  chomp;
  my( $first, @rest ) = split;
  print $first $parts2[$i++] @rest\n;
}

 
 
 $ more file1
 3
 2
 1
 
 $ more file2
 1  2
 3  4
 5  6
 
 **OUTPUT***
 
 1 3   2
 3 2   4
 5 1   6


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




Re: insert

2012-05-07 Thread timothy adigun
Hi lina
On Mon, May 7, 2012 at 8:36 AM, lina lina.lastn...@gmail.com wrote:

 Hi,

 I have two files, one with

 3
 2
 1

 another is:

 3 1
 3 2
 6 3

 How can I insert the first file into the middle of the second file,


   This is one way to do it:

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

my $part1 = get_data( $ARGV[0] );# get f1.txt from CLI
my $part2 = get_data( $ARGV[1] );# get f2.txt from CLI

my $cot = () = @{$part1};
foreach ( 0 .. ( $cot - 1 ) ) {
my @rec = split /\s+/, $part2-[$_];
print $rec[0],   , $part1-[$_],   , $rec[1], $/;
}

sub get_data {
my ($file) = @_;
my $arr_ref = [];
open my $fh, '', $file or die can't open this file: $!;
while ($fh) {
chomp;
push @$arr_ref, $_;
}
close $fh or die can't close file:$!;
return $arr_ref;
}




 Thanks ahead for your suggestions,

 Best regards,

 --
Tim


Re: insert

2012-05-07 Thread John W. Krahn

timothy adigun wrote:


On Mon, May 7, 2012 at 8:36 AM, linalina.lastn...@gmail.com  wrote:


I have two files, one with

3
2
1

another is:

3 1
3 2
6 3

How can I insert the first file into the middle of the second file,


This is one way to do it:

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

my $part1 = get_data( $ARGV[0] );# get f1.txt from CLI
my $part2 = get_data( $ARGV[1] );# get f2.txt from CLI

my $cot = () = @{$part1};


There is no need to copy the array to a list in order to get the number 
of elements in the array because an array in scalar context will return 
the number of elements.




foreach ( 0 .. ( $cot - 1 ) ) {


But you don't need the $cot variable anyways because you can just do this:

foreach ( 0 .. $#$part1 ) {



 my @rec = split /\s+/, $part2-[$_];
 print $rec[0],   , $part1-[$_],   , $rec[1], $/;
}




John
--
Any intelligent fool can make things bigger and
more complex... It takes a touch of genius -
and a lot of courage to move in the opposite
direction.   -- Albert Einstein

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




Re: insert

2012-05-07 Thread timothy adigun
On Mon, May 7, 2012 at 11:29 PM, John W. Krahn jwkr...@shaw.ca wrote:

 timothy adigun wrote:


 On Mon, May 7, 2012 at 8:36 AM, linalina.lastn...@gmail.com  wrote:

  I have two files, one with

 3
 2
 1

 another is:

 3 1
 3 2
 6 3

 How can I insert the first file into the middle of the second file,


This is one way to do it:

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

 my $part1 = get_data( $ARGV[0] );# get f1.txt from CLI
 my $part2 = get_data( $ARGV[1] );# get f2.txt from CLI

 my $cot = () = @{$part1};


 There is no need to copy the array to a list in order to get the number of
 elements in the array because an array in scalar context will return the
 number of elements.



  foreach ( 0 .. ( $cot - 1 ) ) {


 But you don't need the $cot variable anyways because you can just do this:

 foreach ( 0 .. $#$part1 ) {

thanks I know. I just felt like having fun! :-)





insert a . every four characters

2012-03-09 Thread Noah

Hi there,

I am trying to insert a '.' every four characters.  Say I have a $it = 
'123456789012' and want the result to be '1234.5678.9012'


whats one of the smoothest ways to do that?


Cheers,
Noah

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




Re: insert a . every four characters

2012-03-09 Thread Noah

On 3/9/12 8:37 PM, Noah wrote:

Hi there,

I am trying to insert a '.' every four characters. Say I have a $it =
'123456789012' and want the result to be '1234.5678.9012'

whats one of the smoothest ways to do that?



okay I answered my own question.  I am wondering if there is a different 
way?


I did:

$it =~ s/(\S{4})/$1\./g;



Cheers,
Noah





Cheers,
Noah




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




Re: insert a . every four characters

2012-03-09 Thread Owen

 On 3/9/12 8:37 PM, Noah wrote:
 Hi there,

 I am trying to insert a '.' every four characters. Say I have a $it
 =
 '123456789012' and want the result to be '1234.5678.9012'

 whats one of the smoothest ways to do that?


 okay I answered my own question.  I am wondering if there is a
 different
 way?

 I did:

 $it =~ s/(\S{4})/$1\./g;



What is there is only, say 11 characters? Or doesn't that situation arise



 --
Owen


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




Re: insert a . every four characters

2012-03-09 Thread Jim Gibson

At 8:37 PM -0800 3/9/12, Noah wrote:

Hi there,

I am trying to insert a '.' every four characters.  Say I have a $it 
= '123456789012' and want the result to be '1234.5678.9012'


whats one of the smoothest ways to do that?


You could adapt the method suggested by 'perldoc -q commas' How can 
I output my numbers with commas added?



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




How Do I insert a password into a PDF

2011-11-25 Thread Ramprasad Prasad
I am generating pdf files with http://code.google.com/p/wkhtmltopdf/


I want to password protect the PDF's .. How can I do this ?


PERL MYSQL query IF EXISTS then UPDATE else INSERT

2010-10-20 Thread S Pratap Singh
Hello,

I want to update my database if the key value is already there then it will
update the required field else it will insert the new row in the same table.


Insert query works fine but I am not able to figure out how to achieve this
IF EXISTS then UPDATE else INSERT  using a one liner MYSQL statement . If
someone can give me an example to write such query and execute it from perl
then it would be really appreciated.

Thank you.
Pratap


Re: PERL MYSQL query IF EXISTS then UPDATE else INSERT

2010-10-20 Thread Uri Guttman
 SPS == S Pratap Singh kdari...@gmail.com writes:


  SPS Insert query works fine but I am not able to figure out how to
  SPS achieve this IF EXISTS then UPDATE else INSERT using a one
  SPS liner MYSQL statement . If someone can give me an example to
  SPS write such query and execute it from perl then it would be really
  SPS appreciated.

that is an sql question that has nothing to do with perl. please ask it
in an sql forum. the answer that i know is that you can't do it in basic
sql.

uri

-- 
Uri Guttman  --  u...@stemsystems.com    http://www.sysarch.com --
-  Perl Code Review , Architecture, Development, Training, Support --
-  Gourmet Hot Cocoa Mix    http://bestfriendscocoa.com -

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




Re: PERL MYSQL query IF EXISTS then UPDATE else INSERT

2010-10-20 Thread Chris Knipe
Just use SQL?

INSERT INTO tbl, VALUES ('11','22','33') ON DUPLICATE KEY 

http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html



On Wed, Oct 20, 2010 at 9:23 AM, Uri Guttman u...@stemsystems.com wrote:

  SPS == S Pratap Singh kdari...@gmail.com writes:


  SPS Insert query works fine but I am not able to figure out how to
  SPS achieve this IF EXISTS then UPDATE else INSERT using a one
  SPS liner MYSQL statement . If someone can give me an example to
  SPS write such query and execute it from perl then it would be really
  SPS appreciated.

 that is an sql question that has nothing to do with perl. please ask it
 in an sql forum. the answer that i know is that you can't do it in basic
 sql.

 uri

 --
 Uri Guttman  --  u...@stemsystems.com    http://www.sysarch.com--
 -  Perl Code Review , Architecture, Development, Training, Support
 --
 -  Gourmet Hot Cocoa Mix    http://bestfriendscocoa.com-

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





-- 

Regards,
Chris Knipe


Re: PERL MYSQL query IF EXISTS then UPDATE else INSERT

2010-10-20 Thread Peter Scott
On Wed, 20 Oct 2010 12:07:03 +0530, S Pratap Singh wrote:
 I want to update my database if the key value is already there then it
 will update the required field else it will insert the new row in the
 same table.
 
 Insert query works fine but I am not able to figure out how to achieve
 this IF EXISTS then UPDATE else INSERT  using a one liner MYSQL
 statement . If someone can give me an example to write such query and
 execute it from perl then it would be really appreciated.

This isn't a Perl question, you're asking in the wrong place.  This is 
analogous to asking your auto mechanic what the feeding habits of emus 
are because you used your car to drive to the zoo.

-- 
Peter Scott
http://www.perlmedic.com/ http://www.perldebugged.com/
http://www.informit.com/store/product.aspx?isbn=0137001274
http://www.oreillyschool.com/courses/perl1/

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




RE: PERL MYSQL query IF EXISTS then UPDATE else INSERT

2010-10-20 Thread Mimi Cafe
This is the wrong list for MySQL questiosn, but I believe you are probably
looking to replace the matching record, use MySQL INSERT REPLACE INTO
tablename.

Mimi


= -Original Message-
= From: S Pratap Singh [mailto:kdari...@gmail.com]
= Sent: 20 October 2010 07:37
= To: beginners@perl.org
= Subject: PERL MYSQL query IF EXISTS then UPDATE else INSERT
= 
= Hello,
= 
= I want to update my database if the key value is already there then it
= will
= update the required field else it will insert the new row in the same
= table.
= 
= 
= Insert query works fine but I am not able to figure out how to achieve
= this
= IF EXISTS then UPDATE else INSERT  using a one liner MYSQL statement
= . If
= someone can give me an example to write such query and execute it from
= perl
= then it would be really appreciated.
= 
= Thank you.
= Pratap


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




how to insert records into table in oracle database.

2009-01-17 Thread Sureshkumar M (HCL Financial Services)

Hi,
Can some one help me how to insert records into oracle database
tables using Perl script? 

Regards,
Suresh


DISCLAIMER:
---

The contents of this e-mail and any attachment(s) are confidential and intended 
for the named recipient(s) only.
It shall not attach any liability on the originator or HCL or its affiliates. 
Any views or opinions presented in 
this email are solely those of the author and may not necessarily reflect the 
opinions of HCL or its affiliates.
Any form of reproduction, dissemination, copying, disclosure, modification, 
distribution and / or publication of 
this message without the prior written consent of the author of this e-mail is 
strictly prohibited. If you have 
received this email in error please delete it and notify the sender 
immediately. Before opening any mail and 
attachments please check them for viruses and defect.

---

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




Re: how to insert records into table in oracle database.

2009-01-17 Thread Owen

 Hi,
   Can some one help me how to insert records into oracle database
 tables using Perl script?




perldoc DBI is worth the read, then read the driver documentation for
Oracle (it would be something like DBD::Oracle)


Owen





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




Re: insert keyword

2008-11-11 Thread Chas. Owens
On Mon, Nov 10, 2008 at 09:26, Sharan Basappa [EMAIL PROTECTED] wrote:
 Hi,

 I have a string that has value delimited by space
 e.g. 1 2 10 8 etc.

 I need to add a keyword wherever there is a space.
 I wrote a small code to try this out:

 $str = one two three;
 $str =~ s/\s/x /g;

 In this case, I am trying to insert x where there is a space. one two
 three should
 become one x two x three.
 But the above example results in:
 nex twox three (chops off leading o char)

 The interesting this is that this happens only in debug mode.
 The regular output is: onex twox three

I don't know what you call debug mode, so I can't tell you why you
lose your leading character, but, I can tell you that the substitution
is doing exactly what you have told it to.  You are telling it to
replace any white space (not just spaces) characters with x .  If
you want to retain the original character you need to say something
like

$str =~ s/(\s)/${1}x /g;

But you probably really want to say

$str =~ s/ / x /g;

because \s will match all white space characters (i.e. tab, line feed,
form feed, carriage return, space, \x{85}, \x{2028}, and
\x{2029}).

-- 
Chas. Owens
wonkden.net
The most important skill a programmer can have is the ability to read.

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




Re: insert keyword

2008-11-11 Thread Sharan Basappa
 Hi,

 I have a string that has value delimited by space
 e.g. 1 2 10 8 etc.

 I need to add a keyword wherever there is a space.
 I wrote a small code to try this out:

 $str = one two three;
 $str =~ s/\s/x /g;

 In this case, I am trying to insert x where there is a space. one two
 three should
 become one x two x three.
 But the above example results in:
 nex twox three (chops off leading o char)

 The interesting this is that this happens only in debug mode.
 The regular output is: onex twox three

 I don't know what you call debug mode, so I can't tell you why you
 lose your leading character, but, I can tell you that the substitution
 is doing exactly what you have told it to.  You are telling it to
 replace any white space (not just spaces) characters with x .  If
 you want to retain the original character you need to say something
 like

 $str =~ s/(\s)/${1}x /g;

 But you probably really want to say

 $str =~ s/ / x /g;

 because \s will match all white space characters (i.e. tab, line feed,
 form feed, carriage return, space, \x{85}, \x{2028}, and
 \x{2029}).

I am sorry, I was looking at incorrect output.
But yes, it works in both the cases (with perl and perl -d option)

Regards

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




insert keyword

2008-11-10 Thread Sharan Basappa
Hi,

I have a string that has value delimited by space
e.g. 1 2 10 8 etc.

I need to add a keyword wherever there is a space.
I wrote a small code to try this out:

$str = one two three;
$str =~ s/\s/x /g;

In this case, I am trying to insert x where there is a space. one two
three should
become one x two x three.
But the above example results in:
nex twox three (chops off leading o char)

The interesting this is that this happens only in debug mode.
The regular output is: onex twox three

Regards

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




Re: insert and query a db

2008-01-16 Thread Tri Trinh
On Jan 7, 12:31 am, [EMAIL PROTECTED] wrote:
 Hi
 I'm trying to write a script that reads the data below, parses it, and
 then inserts it into the info table.

 1:Karl Heiz:1:444-555-:441-551-6661:5:1:1:1
 2:Helmut Schmidt:1:222-333-1234:222-555-4321:2:1:1:1
 3:Udo Lindenberg:3:111-555-1234:111-556-4321:3:0:0:1
 4:Peter Frech:2:333-111-1234:3330-555-4321:2:0:1:0
 5:Peter Schneider:6:333-234-1212:333-321-2323:0:0:1:1

 I created the table info with the following columns:

  COLUMN TYPE   ATTRIBUTES
  ===  === ===
  id  int   PRIMARY KEY
  namevarchar(64)
  gradeint
  phone   varchar(16)
  cell  varchar(16)
  house  int
  car  int

 then inserted the data to the table. When I try to read the data from
 the table and display the fields on the screen, it displays only the
 first 2 elements of each record (id and name) and the following error
 message for all other fields:
 ID:  2
 Name:   Helmut Schmidt
 Use of uninitialized value in printf at ./bonnerRunde.pl line 124.
 Grade:  0
 Use of uninitialized value in printf at ./bonnerRunde.pl line 125.
 Phone:
 Use of uninitialized value in printf at ./bonnerRunde.pl line 126.
 Cell:
 Use of uninitialized value in printf at ./bonnerRunde.pl line 127.
 house:  0
 Use of uninitialized value in printf at ./bonnerRunde.pl line 128.
 car:0

 Help is needed and highly appreciated . I would like also to know if
 this is a good way to read and parse data then insert them in a table?
 or there is a better way?

 Thanks for your help

 Berti

 The script:
 
 use warnings;
 use DBI;

 $driver = DBI:DBM:TEST_DB;
 $user = user;
 $password = user1234;

 #--#
 # Create the table info #
 #--#
 $table = info;
 $dbh = DBI-connect($driver, $user, $password) || die Couldn't
 connect to database:  . DBI-errstr();

 $sqlstmt = create TABLE $table (id int PRIMARY KEY, name varchar(64),
 grade int, phone varchar(16), cell varchar(16), house int, car int);

 $dbh-do($sqlstmt);

 #-#
 # read, parse then insert data into info table #
 #-#

 $stp = 1;
 while (DATA){

 #---#
 # Some control statements #
 #---#
 print STEP-$stp\n;
 ($id, $name, $grade, $phone, $cell, $house, $car) = split(:);
 print \$id = $id   \n;
 print \$name   = $name \n;
 print \$grade  = $grade\n;
 print \$phone  = $phone\n;
 print \$cell   = $cell \n;
 print \$house  = $house\n;
 print \$car= $car  \n;
 print \n;

 $sqlInsertStmt = insert into $table
   (id, name, grade, phone, cell, house, car)
values ($id, $name, $grade, $phone, $cell, $house,
 $car);
 $dbh - do ($sqlInsertStmt);
 $stp++;

 }

 #--#
 # run the query  #
 #--#
 $queryStmt = select * from $table;
 $sth = $dbh - prepare ($queryStmt);
 $sth - execute() || die ERROR:  . DBI - errstr();

 #---#
 # get and display number of rows #
 #---#

 $rn = $sth-rows;
 print \n;
 print ##\n;
 print # Number of rows found in the table \$table\ ( $rn ) #\n;
 print ##\n;

 #--#
 # Format and display the fields   #
 #--#
 while (my @result = $sth - fetchrow_array()){
 #print @result\n;
 printf %s %2d\n, ID:, $result[0];
 printf %s %s \n, Name:  , $result[1];
 printf %s %d \n, Grade: , $result[2];
 printf %s %s \n, Phone: , $result[3];
 printf %s %s \n, Cell:  , $result[4];
 printf %s %d \n, house: , $result[5];
 printf %s %d \n, car:   , $result[6];
 print \n;

 }

 $sth - finish();
 $dbh - disconnect();

Those unitialized values just means that the data aren't inserted
correctly into the database.  When you try to fetch the data, values
comes out as null and perl throws out an error.  The first thing is
trying to see whether you inserted the value correctly by dumping your
tablespace.  Here is an updated code to what you have earlier.

$queryStmt = select * from $table;
$sth = $dbh - prepare ($queryStmt);
$sth - execute() || die ERROR:  . $sth-errstr();
$sth-dump_results if $sth-{NUM_OF_FIELDS};

The statement handle that calls the dump_results function should tell
you whether you inserted the data correctly.  Out put as follows:

'1', 'Karl Heiz', undef, undef, undef

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

2008-01-14 Thread perlmunky
On Jan 11, 2008 6:47 PM, Chris Charley [EMAIL PROTECTED] wrote:


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

 Thanks, I read the page, alongside the wikipedia page and I think I
understand what an sql injection is.  My code follows.  The first section is
for a text suggestion drop-down menu - it produces a selection based on the
current user input in a text box and runs a DBI query to get suggestions for
a user.  The details are passed by a javascript routine to catalyst.

sub _build_suggestion_list {
my ($self, $c) = @_;

my $table_and_col_name = $c-req-params-{column_name};
my $current_text   = $c-req-params-{text_input};

my @well_column_names = @{_get_column_names($c,T1)};
my @gi_column_names   = @{_get_column_names($c,T2)};

my %genuine_columns = ();
for (@gi_column_names)   { $genuine_columns{${$_}[0]} = 1; }
for (@well_column_names) { $genuine_columns{${$_}[0]} = 1; }

#I dont think I need the {1,}
if ($current_text =~ /\:{1,}|\--{1,}|\#{1,}|\;|insert|drop|create|^$/ig)
{
my $tc = ulliInvalid Input (: ; --; #)/li/ul;
$c-res-body($tc);
} else {
if ( exists $genuine_columns{$table_and_col_name}) {
my ($table, $column) = split /\./, $table_and_col_name;
my $model= $c-model(q(DB));
my $dbh  = $model-storage-dbh;

my $select = (select distinct $table\.$column from $table where
$table\.$column LIKE \'\%$current_text\%\');
my $sql_exe = $dbh-prepare($select); $sql_exe-execute();
my $results = $sql_exe-fetchall_arrayref();

my $options = ul;
for (@$results) {
$options .= li${$_}[0]/li;
}
$options .= /ul;
$c-res-body($options);
}else {
my $tc = ulliThe column names are invalid - please see
admin/li/ul;
$c-res-body($tc);
}
}
}

The next section contains the query constructor.  This takes all the user
input from multiple rows (users can create as many as they want).  I have
limited the options but this, i think, doesn't help because someone could
craft their own post and submit that. The query is run in another subroutine
which returns the data to the template toolkit end of things.

sub _query : Local {
my ( $self, $c ) = @_;

my $href_params = ($c-request-parameters());

delete $$href_params{'button'};

my @well_column_names = @{_get_column_names($c,T1)};
my @gi_column_names   = @{_get_column_names($c,T2)};

my %genuine_columns = ();
for (@gi_column_names)   { $genuine_columns{${$_}[0]} = 1; }
for (@well_column_names) { $genuine_columns{${$_}[0]} = 1; }

#Are the columns the ones that they should be?
@{$$href_params{'select_these'}} = grep { $genuine_columns{$_} }
@{$$href_params{'select_these'}};

my $select = ;
if ( ref($$href_params{'select_these'}) =~ 'ARRAY' or
ref($$href_params{'select_these'}) =~ 'REF') {
if ( @{$$href_params{'select_these'}} == 0 ) { $select =  T2.y ;}
else { $select = join( ,, @{$$href_params{'select_these'}}); }
} else {
if ($$href_params{'select_these'} eq ) { $select = T1.x; }
else {
if ( exists $genuine_columns{$$href_params{'select_these'}}) {
$select = $$href_params{'select_these'};
} else {
$select = T1.x;
}
}
}

#Two blocks - one for where there are multiple user conditions and the other
for singles
my $conditional = ;
if ( ref($$href_params{'conditional_type'}) =~ 'ARRAY' or
ref($$href_params{'conditional_type'}) =~ 'REF') {
for (my $i = 0; $i  @{$$href_params{'conditional_type'}}; $i++) {
$conditional .= ${$$href_params{'conditional_type'}}[$i]   .
' ';
$conditional .= ${$$href_params{'select_column_name'}}[$i] .
' ';

#Check for foul play
if (${$$href_params{'user_text'}}[$i] =~
/\;|:|--|#|insert|drop|create|\'|\|null/ig ) {
${$$href_params{'user_text'}}[$i] = null; #This can't
be 'null'
}

if ( ${$$href_params{'case_option'}}[$i] =~ /^like$/ig ) {
$conditional .= ${$$href_params{'case_option'}}[$i]
'\%${$$href_params{'user_text'}}[$i]\%'. ' ';
} else {
$conditional .=
${$$href_params{'case_option'}}[$i]. ' ';
$conditional .=
${$$href_params{'user_text'}}[$i]  . ' ';
}
}
} else {
if ($$href_params{'user_text'} =~
/\;|:|--|#|insert|drop|create|\'|\|null/ig ) {
$$href_params{'user_text'} = null;
}
if ($$href_params{'case_option'} =~ /like/ig) {
$$href_params{'user_text'} =
'\%$$href_params{'user_text

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

2008-01-14 Thread John W. Krahn

perlmunky wrote:

On Jan 11, 2008 6:47 PM, Chris Charley [EMAIL PROTECTED] wrote:


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

Thanks, I read the page, alongside the wikipedia page and I think I

understand what an sql injection is.  My code follows.  The first section is
for a text suggestion drop-down menu - it produces a selection based on the
current user input in a text box and runs a DBI query to get suggestions for
a user.  The details are passed by a javascript routine to catalyst.

sub _build_suggestion_list {
my ($self, $c) = @_;

my $table_and_col_name = $c-req-params-{column_name};
my $current_text   = $c-req-params-{text_input};

my @well_column_names = @{_get_column_names($c,T1)};
my @gi_column_names   = @{_get_column_names($c,T2)};

my %genuine_columns = ();
for (@gi_column_names)   { $genuine_columns{${$_}[0]} = 1; }
for (@well_column_names) { $genuine_columns{${$_}[0]} = 1; }


Why copy two the two arrays when you can just use the references 
directly?  The dereferencing syntax is usually $_-[0] not ${$_}[0]. 
You can remove a lot of the duplication by doing it like this:


my %genuine_columns = map { $_-[0] = 1 }
  map @{ _get_column_names( $c, $_ ) },
  qw/T1 T2/;



#I dont think I need the {1,}
if ($current_text =~ /\:{1,}|\--{1,}|\#{1,}|\;|insert|drop|create|^$/ig)


The characters ':', '-', '#' and ';' are not special in regular 
expressions so they don't have to be escaped.  The quantifier '{1,}' 
could be written more simply as '+'.  The pattern is evaluated in 
boolean context so the /g option is extraneous.




{
my $tc = ulliInvalid Input (: ; --; #)/li/ul;
$c-res-body($tc);
} else {
if ( exists $genuine_columns{$table_and_col_name}) {
my ($table, $column) = split /\./, $table_and_col_name;
my $model= $c-model(q(DB));
my $dbh  = $model-storage-dbh;

my $select = (select distinct $table\.$column from $table where
$table\.$column LIKE \'\%$current_text\%\');


The characters ., ' and % are not special in a double quoted 
string so they don't have to be escaped.




my $sql_exe = $dbh-prepare($select); $sql_exe-execute();
my $results = $sql_exe-fetchall_arrayref();

my $options = ul;
for (@$results) {
$options .= li${$_}[0]/li;


${$_}[0] is usually written as $_-[0].


}
$options .= /ul;
$c-res-body($options);
}else {
my $tc = ulliThe column names are invalid - please see
admin/li/ul;
$c-res-body($tc);
}
}
}

The next section contains the query constructor.  This takes all the user
input from multiple rows (users can create as many as they want).  I have
limited the options but this, i think, doesn't help because someone could
craft their own post and submit that. The query is run in another subroutine
which returns the data to the template toolkit end of things.

sub _query : Local {
my ( $self, $c ) = @_;

my $href_params = ($c-request-parameters());

delete $$href_params{'button'};


$$href_params{'button'} is usually written as $href_params-{button}


my @well_column_names = @{_get_column_names($c,T1)};
my @gi_column_names   = @{_get_column_names($c,T2)};

my %genuine_columns = ();
for (@gi_column_names)   { $genuine_columns{${$_}[0]} = 1; }
for (@well_column_names) { $genuine_columns{${$_}[0]} = 1; }


Same as with the other subroutine:

my %genuine_columns = map { $_-[0] = 1 }
  map @{ _get_column_names( $c, $_ ) },
  qw/T1 T2/;



#Are the columns the ones that they should be?
@{$$href_params{'select_these'}} = grep { $genuine_columns{$_} }
@{$$href_params{'select_these'}};


@{$$href_params{'select_these'}} is usually written as @{ 
$href_params-{ select_these } }


[ The same applies to every other instance where this occurs. ]



my $select = ;
if ( ref($$href_params{'select_these'}) =~ 'ARRAY' or
ref($$href_params{'select_these'}) =~ 'REF') {


You are using '=~' when you should be using 'eq'.

 if ( ref( $href_params-{ select_these } ) eq 'ARRAY' or ref( 
$href_params{ select_these } ) eq 'REF' ) {




if ( @{$$href_params{'select_these'}} == 0 ) { $select =  T2.y ;}
else { $select = join( ,, @{$$href_params{'select_these'}}); }
} else {
if ($$href_params{'select_these'} eq ) { $select = T1.x; }
else {
if ( exists $genuine_columns{$$href_params{'select_these'}}) {
$select = $$href_params{'select_these'};
} else {
$select = T1.x;
}
}
}

#Two blocks - one for where there are multiple user conditions and the other
for singles
my $conditional

Re: insert and query a db

2008-01-11 Thread bbrecht56
On Jan 7, 1:50 pm, [EMAIL PROTECTED] (John Moon) wrote:
  [] ...

 Please try (not tested). Placeholders help me a lot:

 my $sth_insert = $dbh-prepare('Insert into info (id, name, grade,
 phone, cell, house, car)
values (?,?,?,?,?,?,?)')
 or die DBI-errstr;
 while (DATA){

 #---#
 # Some control statements #
 #---#
 print STEP-$stp\n;
 ($id, $name, $grade, $phone, $cell, $house, $car) = split(:);
 print \$id = $id   \n;
 [] ...
 print \$car= $car  \n;
 print \n;

 []die DBI-errstr unless $sth_insert-execute($id, $name,
 $grade, $phone, $cell, $house, $car);

 $stp++;}

 [] ...

Hi John,

Thanks for your reply.
I tried your suggestion with the Placeholder:

my $sqlInsertStmt = insert into $table
  (id, name, grade, phone, cell, house, car)
  values (?, ?, ?, ?, ?, ?, ?);

$sth = $dbh - prepare ($sqlInsertStmt) || die DBI - errstr;
die DBI - errstr unless $sth - execute ($id, $name, $grade, $phone,
$cell, $house, $car);


unfortunately, I get the same error message when I run:

$queryStmt = select * from $table;
$sth = $dbh - prepare ($queryStmt);
$sth - execute() || die ERROR:  . DBI - errstr();

then try to format and print the content of the fields:

while (my @result = $sth - fetchrow_array()){
#print @result\n;
printf %s %2d\n, ID:, $result[0];
printf %s %s \n, Name:  , $result[1];
printf %s %d \n, Grade: , $result[2];
printf %s %s \n, Phone: , $result[3];
printf %s %s \n, Cell:  , $result[4];
printf %s %d \n, house: , $result[5];
printf %s %d \n, car:   , $result[6];
print \n;

Only the content of the first 2 fields is displayed:
ID:  2
Name:   Helmut Schmidt
Use of uninitialized value in printf at ./parseDataIntoDBTable.pl line
75.
Grade:  0
Use of uninitialized value in printf at ./parseDataIntoDBTable.pl line
76.
Phone:
Use of uninitialized value in printf at ./parseDataIntoDBTable.pl line
77.
Cell:
Use of uninitialized value in printf at ./parseDataIntoDBTable.pl line
78.
house:  0
Use of uninitialized value in printf at ./parseDataIntoDBTable.pl line
79.
car:0

Any other idea?
Is there any other way to display the content of the table?

Thanks for your help

Berti


-- 
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 Tom Phoenix
On Jan 11, 2008 6:11 AM, perlmunky [EMAIL PROTECTED] wrote:

 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.

 hints, tips and solutions accepted :)

Have you tried writing Perl code to do the parameter checking? Perl is
generally good at that.

 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.

That sounds like exactly the kind of situation that Perl code could
easily detect and avoid. What have you tried?

Cheers!

--Tom Phoenix
Stonehenge Perl Training

-- 
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: beginners@perl.org
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: insert and query a db

2008-01-11 Thread Tom Phoenix
On Jan 10, 2008 10:50 PM,  [EMAIL PROTECTED] wrote:

 Only the content of the first 2 fields is displayed:

In your shoes, I would check that 'use warnings' and 'use strict' are
in place, and other basics, then I'd start debugging at the database.
Check out the tracing facility, documented in the DBI manpage. Trace
level 2 is probably enough for you to see what's happening from the
db's point of view. Is the db getting the right data? Is it giving the
answers you think it should?

http://search.cpan.org/~timb/DBI/DBI.pm#TRACING

It can also be helpful to step through your code in the Perl debugger.
You can stop at any statement to see what values your variables really
have. That's documented in the perldebug manpage.

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

Good luck with it!

--Tom Phoenix
Stonehenge Perl Training

-- 
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 Tom Phoenix
On Jan 11, 2008 9:43 AM,  [EMAIL PROTECTED] wrote:

 I have written some stuff - I am just concerned that people on the
 big bad web know far more about these things (oracle - perl) than I
 and that they will, with little trouble, side-step my parameter
 checking.

So, show us your code; and we'll help you figure out what's vulnerable
about it, and point you to the documentation on how to do it better.
(If you're even more motivated, you could hunt down the documentation
on your own in the first place. The big bad web has all the answers to
oft answered questions.)

  I was simply after tips from people, such as yourself, on
 the best way of approaching the problem i.e. common pitfalls etc

You remind me of the person who asked the famous author for advice on
writing. The author answered, Start every sentence with a capital
letter, and spell as carefully as you can.

What is your level of knowledge, that we can best help you? You can
best show us your knowledge of Perl by showing us your code.

Cheers!

--Tom Phoenix
Stonehenge Perl Training

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




user arguments, oracle - insert, delete and drop!

2008-01-11 Thread perlmunky
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


insert and query a db

2008-01-07 Thread bbrecht56
Hi
I'm trying to write a script that reads the data below, parses it, and
then inserts it into the info table.

1:Karl Heiz:1:444-555-:441-551-6661:5:1:1:1
2:Helmut Schmidt:1:222-333-1234:222-555-4321:2:1:1:1
3:Udo Lindenberg:3:111-555-1234:111-556-4321:3:0:0:1
4:Peter Frech:2:333-111-1234:3330-555-4321:2:0:1:0
5:Peter Schneider:6:333-234-1212:333-321-2323:0:0:1:1

I created the table info with the following columns:

 COLUMN TYPE   ATTRIBUTES
 ===  === ===
 id  int   PRIMARY KEY
 namevarchar(64)
 gradeint
 phone   varchar(16)
 cell  varchar(16)
 house  int
 car  int

then inserted the data to the table. When I try to read the data from
the table and display the fields on the screen, it displays only the
first 2 elements of each record (id and name) and the following error
message for all other fields:
ID:  2
Name:   Helmut Schmidt
Use of uninitialized value in printf at ./bonnerRunde.pl line 124.
Grade:  0
Use of uninitialized value in printf at ./bonnerRunde.pl line 125.
Phone:
Use of uninitialized value in printf at ./bonnerRunde.pl line 126.
Cell:
Use of uninitialized value in printf at ./bonnerRunde.pl line 127.
house:  0
Use of uninitialized value in printf at ./bonnerRunde.pl line 128.
car:0

Help is needed and highly appreciated . I would like also to know if
this is a good way to read and parse data then insert them in a table?
or there is a better way?

Thanks for your help

Berti


The script:

use warnings;
use DBI;

$driver = DBI:DBM:TEST_DB;
$user = user;
$password = user1234;

#--#
# Create the table info #
#--#
$table = info;
$dbh = DBI-connect($driver, $user, $password) || die Couldn't
connect to database:  . DBI-errstr();

$sqlstmt = create TABLE $table (id int PRIMARY KEY, name varchar(64),
grade int, phone varchar(16), cell varchar(16), house int, car int);

$dbh-do($sqlstmt);

#-#
# read, parse then insert data into info table #
#-#

$stp = 1;
while (DATA){

#---#
# Some control statements #
#---#
print STEP-$stp\n;
($id, $name, $grade, $phone, $cell, $house, $car) = split(:);
print \$id = $id   \n;
print \$name   = $name \n;
print \$grade  = $grade\n;
print \$phone  = $phone\n;
print \$cell   = $cell \n;
print \$house  = $house\n;
print \$car= $car  \n;
print \n;

$sqlInsertStmt = insert into $table
  (id, name, grade, phone, cell, house, car)
   values ($id, $name, $grade, $phone, $cell, $house,
$car);
$dbh - do ($sqlInsertStmt);
$stp++;
}

#--#
# run the query  #
#--#
$queryStmt = select * from $table;
$sth = $dbh - prepare ($queryStmt);
$sth - execute() || die ERROR:  . DBI - errstr();

#---#
# get and display number of rows #
#---#

$rn = $sth-rows;
print \n;
print ##\n;
print # Number of rows found in the table \$table\ ( $rn ) #\n;
print ##\n;

#--#
# Format and display the fields   #
#--#
while (my @result = $sth - fetchrow_array()){
#print @result\n;
printf %s %2d\n, ID:, $result[0];
printf %s %s \n, Name:  , $result[1];
printf %s %d \n, Grade: , $result[2];
printf %s %s \n, Phone: , $result[3];
printf %s %s \n, Cell:  , $result[4];
printf %s %d \n, house: , $result[5];
printf %s %d \n, car:   , $result[6];
print \n;
}

$sth - finish();
$dbh - disconnect();


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




RE: insert and query a db

2008-01-07 Thread Moon, John
 [] ...

Please try (not tested). Placeholders help me a lot:

my $sth_insert = $dbh-prepare('Insert into info (id, name, grade,
phone, cell, house, car)
   values (?,?,?,?,?,?,?)')
or die DBI-errstr;
while (DATA){

#---#
# Some control statements #
#---#
print STEP-$stp\n;
($id, $name, $grade, $phone, $cell, $house, $car) = split(:);
print \$id = $id   \n;
[] ...
print \$car= $car  \n;
print \n;

[]die DBI-errstr unless $sth_insert-execute($id, $name,
$grade, $phone, $cell, $house, $car);

$stp++;
}
[] ...
 

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




Re: Tk question about -command=sub{} and Text Insert()

2007-11-19 Thread Panda-X
2007/11/19, zentara [EMAIL PROTECTED]:

 On Mon, 19 Nov 2007 00:14:29 +0800, [EMAIL PROTECTED] (Panda-X)
 wrote:

 Hi all,
 
 Below is my code. With this code, 12345 will show at once
 after 5 seconds I click the button.
 But what I want is to insert() each number per second.
 Is that something I can do like $| = 1 in such case ?
 
 At least, could anybody tell this is the behavior of insert () ?
 or it's the behavior of -command = sub {} ?
 
 Thank you very much !
 ==

 It would be nice if you posted a complete running example,
 because it's hard to say whether it's Text widget update problem,
 OR the way you setup the class.
 Usually, in your case, the problem is solved by putting an update
 right after the text insert, this forces the Text widget to update
 itself immediately. But you may need to update the $mw too, since
 it's a class.

 sub RollText{
 for ( 1..5 ) {
   $_[0] -{mw}{box} - insert ( 'end', $_ ) ;
  #  sleep 1;
  $_[0] -{mw}{box}-update;

  #or possibly you need to tell the $mw to update the class
  $_[0] -{mw}-update;

 }
 }

 zentara

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


THANK YOU!!! That's exactly what I want !!!
Again, THANK YOU VERY MUCH =)


Tk question about -command=sub{} and Text Insert()

2007-11-18 Thread Panda-X
Hi all,

Below is my code. With this code, 12345 will show at once
after 5 seconds I click the button.
But what I want is to insert() each number per second.
Is that something I can do like $| = 1 in such case ?

At least, could anybody tell this is the behavior of insert () ?
or it's the behavior of -command = sub {} ?

Thank you very much !
==

use Tk;

sub SetButton {
$_[0]-{mw} - Button ( -text='click me',
-command = sub { $_[0] -RollText() }
)   - pack ();
}

sub RollText{
for ( 1..5 ) {
  $_[0] -{mw}{box} - insert ( 'end', $_ ) ;
  sleep 1;
}
}

sub SetText {
$_[0]-{mw}{box} = $class-{mw} - Text ( -width = 10 , -height = 10 )
- pack();
}

sub Build {
my $self = {} ;
$self - {mw} = MainWindow - new ( -title = 'goodbye world' ) ;
return bless $self ;
}

my $class = Build ();
$class - SetText ;
$class - SetButton ;
MainLoop();


Re: Tk question about -command=sub{} and Text Insert()

2007-11-18 Thread Tom Phoenix
On 11/18/07, Panda-X [EMAIL PROTECTED] wrote:

 But what I want is to insert() each number per second.

 sub RollText{
 for ( 1..5 ) {
   $_[0] -{mw}{box} - insert ( 'end', $_ ) ;
   sleep 1;
 }
 }

You probably don't want sleep() there; the after() method is generally
the way to ask Tk to make something happen after some time interval
has passed. The interface is different than simply sleeping, but more
powerful; check the Tk docs for the full story.

Hope this helps!

--Tom Phoenix
Stonehenge Perl Training

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




Re: Tk question about -command=sub{} and Text Insert()

2007-11-18 Thread Panda-X
2007/11/19, Tom Phoenix [EMAIL PROTECTED]:

 On 11/18/07, Panda-X [EMAIL PROTECTED] wrote:

  But what I want is to insert() each number per second.

  sub RollText{
  for ( 1..5 ) {
$_[0] -{mw}{box} - insert ( 'end', $_ ) ;
sleep 1;
  }
  }

 You probably don't want sleep() there; the after() method is generally
 the way to ask Tk to make something happen after some time interval
 has passed. The interface is different than simply sleeping, but more
 powerful; check the Tk docs for the full story.

 Hope this helps!

 --Tom Phoenix
 Stonehenge Perl Training



Thanks Tom,

As you said, I don't really want to sleep. =)  In this code, I am trying to
prove
the sort of insert () will only prompt after everything is done. And what I
want
to understand more is how can I get an immediate insert(), rather than wait
until all done! Any more clues ?

Thank you very much !


Re: Tk question about -command=sub{} and Text Insert()

2007-11-18 Thread Tom Phoenix
On 11/18/07, Panda-X [EMAIL PROTECTED] wrote:
 Any more clues ?

This is a forum for Perl beginners, but there are forums available
specifically for all of the major modules used with Perl. Some modules
have more than one forum. As you might expect, you'll generally get
better answers faster by inquiring in a more specific forum.

Forums are most commonly mailing lists or web-based discussion boards.
Instructions on how to find a forum can generally be found in the FAQ
or main page of the module's documentation. If you don't find it
there, try your favorite search engine after you check the Perl
Mailing List Database:

http://lists.cpan.org/

Many forums have their own FAQ; save time by searching for that before
even subscribing to a mailing list or signing up on a discussion
board. Even if the FAQ doesn't answer your question, it probably
answers questions you didn't know you had; skimming the list of
questions can be educational.

Besides the FAQ, the archives of the forum itself may be searchable
via your favorite search engine. Unless you've got a really new
question, the answer is often out there already.

Have fun with it!

--Tom Phoenix
Stonehenge Perl Training

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




how to insert rows into database from array/hash using DBI

2007-10-23 Thread petelink1
I'm trying to grab data from an MS-Access log file and put it into a
fast, read-only database. (I'm thinking SQL Lite at this point.)

The code below is working.  Now I need to put the identical data and
structure into an SQL Lite table.  Any suggestions on where to look
for examples?  (or if you want to write one, that's fine too.)

I own the book Programming the Perl DBI, but I haven't found
anything that addresses this.

use warnings;
use strict;

use DBI;
use DBD::ODBC;
use DBD::SQLite;

my $DSN = 'driver=Microsoft Access Driver (*.mdb);dbq=C:\temp
\adt2_in.mdb';
my $dbh1 = DBI-connect(dbi:ODBC:$DSN,,) or die $DBI::errstr\n;

$dbh1-{LongReadLen} = 2000;
$dbh1-{LongTruncOk} = 1;

my $sth1 = $dbh1-prepare(select message_index, message_no,
message_event, time_stamp, data from log);

$sth1-execute();

my @stash;

while (my $hash_ref = $sth1-fetchrow_hashref()) {
push @stash, { %$hash_ref };
}

$dbh1-disconnect();

my $itemp = 1;
foreach my $hash_ref (@stash) {
print  Details of row $itemp: ;
print \n\n;

foreach my $key (keys %{$hash_ref}) {
   print ($key \t $hash_ref-{$key} \n);
}
   $itemp++;
}

Thanks.


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




Re: how to insert rows into database from array/hash using DBI

2007-10-23 Thread Gunnar Hjalmarsson

[EMAIL PROTECTED] wrote:

I'm trying to grab data from an MS-Access log file and put it into a
fast, read-only database. (I'm thinking SQL Lite at this point.)

The code below is working.  Now I need to put the identical data and
structure into an SQL Lite table.  Any suggestions on where to look
for examples?


The documentation for the DBD::SQLite module, perhaps?

It may be as simple as just modifying the DBI-connect statement.

--
Gunnar Hjalmarsson
Email: http://www.gunnar.cc/cgi-bin/contact.pl

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




Re: how to insert rows into database from array/hash using DBI

2007-10-23 Thread Matthew Whipple
[EMAIL PROTECTED] wrote:
 I'm trying to grab data from an MS-Access log file and put it into a
 fast, read-only database. (I'm thinking SQL Lite at this point.)
   
Make sure that's it's only read-only after it's written to.  Depending
on what you're doing with the data it may be easiest and fastest to use
a format that Access can work with and then dump directly to that file
with something like a SELECT...INTO... statement and a linked table in
Access.
 The code below is working.  Now I need to put the identical data and
 structure into an SQL Lite table.  Any suggestions on where to look
 for examples?  (or if you want to write one, that's fine too.)

 I own the book Programming the Perl DBI, but I haven't found
 anything that addresses this.

 use warnings;
 use strict;

 use DBI;
 use DBD::ODBC;
 use DBD::SQLite;

 my $DSN = 'driver=Microsoft Access Driver (*.mdb);dbq=C:\temp
 \adt2_in.mdb';
 my $dbh1 = DBI-connect(dbi:ODBC:$DSN,,) or die $DBI::errstr\n;

 $dbh1-{LongReadLen} = 2000;
 $dbh1-{LongTruncOk} = 1;

 my $sth1 = $dbh1-prepare(select message_index, message_no,
 message_event, time_stamp, data from log);

 $sth1-execute();

 my @stash;

 while (my $hash_ref = $sth1-fetchrow_hashref()) {
 push @stash, { %$hash_ref };
 }

 $dbh1-disconnect();

 my $itemp = 1;
 foreach my $hash_ref (@stash) {
 print  Details of row $itemp: ;
 print \n\n;

 foreach my $key (keys %{$hash_ref}) {
print ($key \t $hash_ref-{$key} \n);
 }
$itemp++;
 }

 Thanks.


   


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




Re: How to insert data onto an existing XML file

2007-10-08 Thread Jenda Krynicky
 Jenda Krynicky wrote:
  On 2 Oct 2007 at 10:54, Matthew Whipple wrote:

  You can't really strictly append to a well-formed XML without
  breaking the syntax.  You need the properly closed top level element
  at the very least, in addition to whatever nesting may be going on. 
  
 

  An ugly solution would be to chop off the end of whatever file you're
  dealing with and then recreate it (assuming you know what the end of
  the file looks like).  
  
 
  If you only have to bend backwards because the bright omnipotent 
  creators of the XML standard thought it would be fun to force you to 
  and the whole end-of-the-file that you need to chop off is a 
  /roottag then it's actually the best solution. No matter what 
  would the XML purists love you believe.
 
  The requirement of a root tag in XML is ... yet another lovely 
  misfeature of the format.


From: Matthew Whipple [EMAIL PROTECTED]
 XML apparently just isn't for you.  The closing root tag, if nothing
 else, ensures that the document is whole and simplifies the parsing and
 data format integrity which are large concerns of XML. 

Thanks for proving my point about the purists. If the designers of 
the XML had a bit less of the we know what's best for you 
mentality, they might allow us to specify whether we want to allow 
just one root tag (and thus let the parser test whether the file is 
complete) or not in the DTD or schema. So that the fact that our 
needs do not match their exact expectations, doesn't mean we have use 
something completely different. 

Besides you only get the the document is complete test done in time 
if you use DOM or something else that first parses the whole XML and 
only the lets you access the data. As soon as you move to SAX or 
something like that, you are on your own. You either have to test the 
file completeness yourself before you start the parser or you have to 
make sure you can rollback all changes done by the code that 
processed the part of the XML that was there already. Or parse the 
file twice, once to validate it and second time to process it.

 If the structure
 of the format seems counter-intuitive to what you're doing then use
 something else and optionally export XML for features you may be
 interested in.  It doesn't fit everywhere.

That's all nice except that 1) sometimes you do not get to choose and 
2) sometimes your needs fit just great except ... except from some 
tiny little thing.

From: Bob McConnell [EMAIL PROTECTED]:

 In the end, you have to understand that XML is a hierarchical
 structure. You can't simply append data, it must be inserted at the
 correct level in the hierarchy. 

 foobarx/barbary/bar/foofoobarXXX/bar/foo

is just as hierarchic as

 
rootfoobarx/barbary/bar/foofoobarXXX/bar/foo/ro
ot

The only difference is that in the first case the root tag is not 
explicitely specified.

And that if all you need to do is to add yet another foo tag at the 
end, you in the first case only have to append it while in the second 
you can either chop off the /root (which is unclean) or parse and 
rewrite everything. 

Sometimes the correct level in hierarchy is right at the root.

Jenda
= [EMAIL PROTECTED] === http://Jenda.Krynicky.cz =
When it comes to wine, women and song, wizards are allowed 
to get drunk and croon as much as they like.
-- Terry Pratchett in Sourcery


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




Re: How to insert data onto an existing XML file

2007-10-03 Thread Jenda Krynicky
On 2 Oct 2007 at 10:54, Matthew Whipple wrote:
 You can't really strictly append to a well-formed XML without
 breaking the syntax.  You need the properly closed top level element
 at the very least, in addition to whatever nesting may be going on. 

 An ugly solution would be to chop off the end of whatever file you're
 dealing with and then recreate it (assuming you know what the end of
 the file looks like).  

If you only have to bend backwards because the bright omnipotent 
creators of the XML standard thought it would be fun to force you to 
and the whole end-of-the-file that you need to chop off is a 
/roottag then it's actually the best solution. No matter what 
would the XML purists love you believe.

 A better solution would be to read the previous
 file and generate a new XML document.

Which may be fine for small enough files, but is simply crazy for 
anything longer. Parse and rewrite something to insert something in 
the middle is something that can't be helped, but reparsing and 
recreating everything for APPEND?

The requirement of a root tag in XML is ... yet another lovely 
misfeature of the format.

Jenda

= [EMAIL PROTECTED] === http://Jenda.Krynicky.cz =
When it comes to wine, women and song, wizards are allowed 
to get drunk and croon as much as they like.
-- Terry Pratchett in Sourcery


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




RE: How to insert data onto an existing XML file

2007-10-03 Thread Bob McConnell
 -Original Message-
 From: Jenda Krynicky [mailto:[EMAIL PROTECTED] 
 Sent: Wednesday, October 03, 2007 6:12 AM
 To: beginners@perl.org
 Subject: Re: How to insert data onto an existing XML file
 
 On 2 Oct 2007 at 10:54, Matthew Whipple wrote:
  An ugly solution would be to chop off the end of whatever 
 file you're
  dealing with and then recreate it (assuming you know what the end of
  the file looks like).  
 
 If you only have to bend backwards because the bright omnipotent 
 creators of the XML standard thought it would be fun to force you to 
 and the whole end-of-the-file that you need to chop off is a 
 /roottag then it's actually the best solution. No matter what 
 would the XML purists love you believe.
 
  A better solution would be to read the previous
  file and generate a new XML document.
 
 Which may be fine for small enough files, but is simply crazy for 
 anything longer. Parse and rewrite something to insert something in 
 the middle is something that can't be helped, but reparsing and 
 recreating everything for APPEND?
 
 The requirement of a root tag in XML is ... yet another lovely 
 misfeature of the format.
 
 Jenda

If XML is causing you problems, perhaps you should not be using it?

In the end, you have to understand that XML is a hierarchical structure.
You can't simply append data, it must be inserted at the correct level
in the hierarchy. How difficult that is depends on the schema or DTD
being used. It may be possible to simply chop off a couple of closing
tags, insert your new data and restore the tags behind it. But again,
the code needs to be smart enough to know which tags need to be where in
order to insure the results are still well formed.

If the file is too big, perhaps SAX is a better option that DOM.

Bob McConnell

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




Re: How to insert data onto an existing XML file

2007-10-03 Thread Ken Foskey

On Wed, 2007-10-03 at 00:42 +0800, Steven Sim wrote:
 Gurus;
 
 Sorry if this is not the proper forum.
 
 I've successfully written a Perl script to create a specific XML file.
 
 The problem comes when I attempt to run the script again and append XML 
 entries onto the XML file.
 
 Using XML::Writer, I am unable to perform a proper append. (The append 
 IO is successful but it breaks the XML syntax.)

Design problem more than a programming problem.  Had similar issue with
RSS feeds,  simple approach was to append the XML segment onto the
bottom of the file and then create a new 'working' file by simply
concatenating the main file with the trailer:

File 1

head
record value=1/
record value=2/

File 2

/head

You can append record value=3/ to file 1 and then concat File 1 and
File 2 to create the actual final XML file.  In our case creating the
final static file in the web browser.

-- 
Ken Foskey
FOSS developer


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




Re: How to insert data onto an existing XML file

2007-10-03 Thread Matthew Whipple
Jenda Krynicky wrote:
 On 2 Oct 2007 at 10:54, Matthew Whipple wrote:
   
 You can't really strictly append to a well-formed XML without
 breaking the syntax.  You need the properly closed top level element
 at the very least, in addition to whatever nesting may be going on. 
 

   
 An ugly solution would be to chop off the end of whatever file you're
 dealing with and then recreate it (assuming you know what the end of
 the file looks like).  
 

 If you only have to bend backwards because the bright omnipotent 
 creators of the XML standard thought it would be fun to force you to 
 and the whole end-of-the-file that you need to chop off is a 
 /roottag then it's actually the best solution. No matter what 
 would the XML purists love you believe.

   
 A better solution would be to read the previous
 file and generate a new XML document.
 

 Which may be fine for small enough files, but is simply crazy for 
 anything longer. Parse and rewrite something to insert something in 
 the middle is something that can't be helped, but reparsing and 
 recreating everything for APPEND?

   
If you're dealing with long enough XML files that recreating them isn't
efficient enough for your needs, then your primary source of information
shouldn't be this mailing list.

 The requirement of a root tag in XML is ... yet another lovely 
 misfeature of the format.
   
XML apparently just isn't for you.  The closing root tag, if nothing
else, ensures that the document is whole and simplifies the parsing and
data format integrity which are large concerns of XML.  If the structure
of the format seems counter-intuitive to what you're doing then use
something else and optionally export XML for features you may be
interested in.  It doesn't fit everywhere.

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




How to insert data onto an existing XML file

2007-10-02 Thread Steven Sim

Gurus;

Sorry if this is not the proper forum.

I've successfully written a Perl script to create a specific XML file.

The problem comes when I attempt to run the script again and append XML 
entries onto the XML file.


Using XML::Writer, I am unable to perform a proper append. (The append 
IO is successful but it breaks the XML syntax.)


Could some guru here share the logic of appending data onto an existing 
XML file using XML::Writer?


(Using it to create a brand new XML file is easy. It's the appending 
that is really giving me a headache).


Warmest Regards
Steven Sim






Fujitsu Asia Pte. Ltd.
_

This e-mail is confidential and may also be privileged. If you are not the intended recipient, please notify us immediately. You should not copy or use it for any purpose, nor disclose its contents to any other person. 


Opinions, conclusions and other information in this message that do not relate 
to the official business of my firm shall be understood as neither given nor 
endorsed by it.



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




Re: How to insert data onto an existing XML file

2007-10-02 Thread Matthew Whipple
You can't really strictly append to a well-formed XML without breaking
the syntax.  You need the properly closed top level element at the very
least, in addition to whatever nesting may be going on.  An ugly
solution would be to chop off the end of whatever file you're dealing
with and then recreate it (assuming you know what the end of the file
looks like).  A better solution would be to read the previous file and
generate a new XML document.  Probably the best solution (assuming the
file is big enough or the operation intricate enough to merit it) would
be to write some wrapper functions for your specific XML scheme which
will ensure that the document syntax is what is expected, and then
insert the elements in the proper location (most likely using another
module in place of or in addition to XML::Writer). 

Steven Sim wrote:
 Gurus;

 Sorry if this is not the proper forum.

 I've successfully written a Perl script to create a specific XML file.

 The problem comes when I attempt to run the script again and append
 XML entries onto the XML file.

 Using XML::Writer, I am unable to perform a proper append. (The append
 IO is successful but it breaks the XML syntax.)

 Could some guru here share the logic of appending data onto an
 existing XML file using XML::Writer?

 (Using it to create a brand new XML file is easy. It's the appending
 that is really giving me a headache).

 Warmest Regards
 Steven Sim






 Fujitsu Asia Pte. Ltd.
 _

 This e-mail is confidential and may also be privileged. If you are not
 the intended recipient, please notify us immediately. You should not
 copy or use it for any purpose, nor disclose its contents to any other
 person.
 Opinions, conclusions and other information in this message that do
 not relate to the official business of my firm shall be understood as
 neither given nor endorsed by it.





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




Re: How to insert data onto an existing XML file

2007-10-02 Thread Tom Phoenix
On 10/2/07, Steven Sim [EMAIL PROTECTED] wrote:

 I've successfully written a Perl script to create a specific XML file.

 The problem comes when I attempt to run the script again and append XML
 entries onto the XML file.

 Using XML::Writer, I am unable to perform a proper append. (The append
 IO is successful but it breaks the XML syntax.)

XML syntax is such that, once a file is complete, more data can't be
appended. The general solution is to write a new XML file that
includes everything you need, then replace the old file with the new
one.

Hope this helps!

--Tom Phoenix
Stonehenge Perl Training

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




Re: database insert algorithm

2007-09-24 Thread Jenda Krynicky
From: Luke [EMAIL PROTECTED]
 Hello,
 I am looking for a proper, fastest and most reasonable way to insert
 data from pretty big file (~1,000,000 lines) to database. I am using
 Win32::ODBC (ActiveState Perl) module to connect with Access/MSSQL
 database and inserting line after line. I was wondering if there is a
 better way to do it...
 Maybe create hash with part of data (maybe all of it - what are the
 limitations ?)
 What is other way to do it instead 'INSERT INTO...' statement after
 reading each line ?

I you stick to Perl, you should use DBI and DBD::ODBC, not 
Win32::ODBC. You should use -prepare() and -execute(). And you 
should turn the AutoCommit off and commit only every 100 or 1000 
rows.

Jenda
= [EMAIL PROTECTED] === http://Jenda.Krynicky.cz =
When it comes to wine, women and song, wizards are allowed 
to get drunk and croon as much as they like.
-- Terry Pratchett in Sourcery


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




Re: database insert algorithm

2007-09-24 Thread Rob Coops
First of all, you should try and use the database native tools for loading
tables this size...

If it has to be perl which does happen sometimes, you should definetly
switch of autocommit. Try doing a commit every 5 lines or even every
10 lines (ask your friendly DBA how big the transaction log and rollback
segment are and if they will support the 100k or if maybe 50k or 25k would
be better), the bigger the block the less the overhead. Also ask you DBA to
consider table locks and so on when doing an insert this big...

Then you should if at all posible prepare the insert statment so you just
have to give the variables before doing the execute, this will save a lot on
the overhead.

Then of course if you have the memory try and shove as much of the variables
in memory while the commit is being executed, you might be able to use two
threads one to read a chunk and one to shove the stuff in the database,
while the other is reading a new chunk.

Regards,

Rob


On 9/22/07, Luke [EMAIL PROTECTED] wrote:

 Hello,
 I am looking for a proper, fastest and most reasonable way to insert
 data from pretty big file (~1,000,000 lines) to database. I am using
 Win32::ODBC (ActiveState Perl) module to connect with Access/MSSQL
 database and inserting line after line. I was wondering if there is a
 better way to do it...
 Maybe create hash with part of data (maybe all of it - what are the
 limitations ?)
 What is other way to do it instead 'INSERT INTO...' statement after
 reading each line ?

 Thanks for any help in advance...

 Luke


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





Re: database insert algorithm

2007-09-24 Thread Matthew Whipple
I haven't dealt with MS databases in several years but some of this
stuff will likely still apply.  First a couple notes on the underlying
databases, if you're running Access be sure to compact the database
after the insert particularly if this is going to be a repeated process,
in addition to the gained performance there may be a file size
limitation and the file can swell incredibly during a large insert If
you're running MS SQL then make sure that the cluster index on the table
isn't set up in a way that the insert will require a lot of rearranging
of data.
If you can take the table off line during the insert the best
solution would be to use Perl to dump the data into a standard format
(if it isn't already) and use the databases native importing tools.  If
you are going to be inserting with the DB online then depending on the
quantity of data and how much the DB is accessed, then record locking
during inserts/updates can create a serious lag.  My suggested solution
for this scenario would be to create long INSERT statements which will
add multiple rows at a time...most SQL databases support some form of
this with something along the lines of multiple sets of values in
parentheses but the specific command format varies.  You can tailor the
number of lines to suit your need, balancing the extra speed of the
fewer, larger database transactions with momentarily freeing up the
system.  The smaller inserts can also cause problems if they're not
getting processed by the DB fast enough and end up backed up.  I think
MS SQL at least also allows for the setting of precedence for certain
SQL statements or processes, and creating a stored procedure may provide
an additional performance boost. 

Luke wrote:
 Hello,
 I am looking for a proper, fastest and most reasonable way to insert
 data from pretty big file (~1,000,000 lines) to database. I am using
 Win32::ODBC (ActiveState Perl) module to connect with Access/MSSQL
 database and inserting line after line. I was wondering if there is a
 better way to do it...
 Maybe create hash with part of data (maybe all of it - what are the
 limitations ?)
 What is other way to do it instead 'INSERT INTO...' statement after
 reading each line ?

 Thanks for any help in advance...

 Luke


   


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




Re: database insert algorithm

2007-09-23 Thread Dr.Ruud
Luke schreef:

 I am looking for a proper, fastest and most reasonable way to insert
 data from pretty big file (~1,000,000 lines) to database.

Make the file have a format as needed by the data import tool of the
database system.
Often a CSV format is supported.

See also bcp:
http://technet.microsoft.com/en-us/library/ms162802.aspx

-- 
Affijn, Ruud

Gewoon is een tijger.


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




Re: database insert algorithm

2007-09-23 Thread [EMAIL PROTECTED]
On 22 Sep, 02:58, [EMAIL PROTECTED] (Luke) wrote:
 Hello,
 I am looking for a proper, fastest and most reasonable way to insert
 data from pretty big file (~1,000,000 lines) to database. I am using
 Win32::ODBC (ActiveState Perl) module to connect with Access/MSSQL
 database and inserting line after line. I was wondering if there is a
 better way to do it...
 Maybe create hash with part of data (maybe all of it - what are the
 limitations ?)
 What is other way to do it instead 'INSERT INTO...' statement after
 reading each line ?

DBI has an execute_array method that can allow DBD drivers to optimize
such operations.

Unfortunately AFAIK none of the DBD drivers I've encountered do any
significant  optimisation.

For efficient bulk inserts I usually fall back on writing a file and
using the underlying database's bulk insert tool. This, of course,
does not give portability between databases.


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




database insert algorithm

2007-09-22 Thread Luke
Hello,
I am looking for a proper, fastest and most reasonable way to insert
data from pretty big file (~1,000,000 lines) to database. I am using
Win32::ODBC (ActiveState Perl) module to connect with Access/MSSQL
database and inserting line after line. I was wondering if there is a
better way to do it...
Maybe create hash with part of data (maybe all of it - what are the
limitations ?)
What is other way to do it instead 'INSERT INTO...' statement after
reading each line ?

Thanks for any help in advance...

Luke


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




How to insert an array in to the middle of another array after a certain pattern

2007-04-13 Thread Typos

Hello everyone,

I'm a Perl beginner and I've been trying for a while to to insert an array
in to the middle of another array after a certain pattern.
Here is what I'm trying to do...I have the Linux Iptables configuration
file, which has a custom chain called MAC which hold all the IP to MAC
entries mappings. Since I update the list manually, I usually end up with IP
addresses here and there...I managed to put all the sorted IP to MAC entries
on a seperate array, and then remove all the MAC entries from the original
file...So what I basically need to do is insert the sorted iptables array
between the INPUT and OUTPUT chains. Here is a sample output of the array,
when all MAC entries are removed...

# Generated by iptables-save v1.3.0 on Wed Jan 17 10:35:18 2007
*filter
:FORWARD DROP [7:336]
:INPUT DROP [11:904]
:MAC - [0:0]
:OUTPUT DROP [7:7994]
-A FORWARD -p icmp -j ACCEPT
-A FORWARD -s 192.168.0.222 -j ACCEPT
-A FORWARD -s 192.168.0.25 -j ACCEPT
-A FORWARD -s 192.168.0.15 -j ACCEPT
-A FORWARD -s 192.168.0.74 -j ACCEPT
-A FORWARD -s 192.168.0.33 -j ACCEPT
-A FORWARD -s 192.168.0.247 -j ACCEPT
-A FORWARD -s 192.168.0.36 -j ACCEPT
-A FORWARD -s 192.168.0.17 -j ACCEPT
-A FORWARD -s 192.168.0.182 -j ACCEPT
-A FORWARD -s 192.168.0.99 -j ACCEPT
-A FORWARD -s 192.168.0.97 -p tcp --dport 9099 -j ACCEPT
-A FORWARD -s 192.168.0.18 -p tcp -m tcp --dport 21 -j ACCEPT
-A FORWARD -p tcp -m tcp --dport 22 -j MAC
-A FORWARD -p udp -m udp --dport 53 -j ACCEPT
-A FORWARD -p tcp -m tcp --dport 110 -j MAC
-A FORWARD -p tcp -m tcp --dport 6346 -j ACCEPT
-A FORWARD -s 192.168.0.204 -p tcp -m tcp --dport 21 -j ACCEPT
-A FORWARD -p tcp -m tcp --dport 22 -j MAC
-A FORWARD -p tcp -m tcp --dport 6667 -j MAC
-A FORWARD -s 192.168.0.204 -p tcp -m tcp --dport 995 -j MAC
-A FORWARD -s 192.168.0.204 -p tcp -m tcp --dport 465 -j MAC
-A FORWARD -m state --state RELATED,ESTABLISHED -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -i eth1 -p icmp -j ACCEPT
-A INPUT -i eth1 -p tcp -m tcp --dport 22 -j MAC
-A INPUT -p tcp -m tcp --dport 25 -j MAC
-A INPUT -i eth1 -p tcp -m tcp --dport 8080 -j MAC
-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
-A OUTPUT -o lo -j ACCEPT
-A OUTPUT -p icmp -j ACCEPT
-A OUTPUT -p tcp -m tcp --sport 22 -j ACCEPT
-A OUTPUT -p tcp -m tcp --dport 22 -j ACCEPT
-A OUTPUT -p tcp -m tcp --dport 25 -j ACCEPT
-A OUTPUT -p udp -m udp --dport 53 -j ACCEPT
-A OUTPUT -p tcp -m tcp --dport 80 -j ACCEPT
-A OUTPUT -p tcp -m tcp --dport 443 -j ACCEPT
-A OUTPUT -p tcp -m tcp --dport 2020 -j ACCEPT
-A OUTPUT -p tcp -m tcp --dport 2082 -j ACCEPT
-A OUTPUT -p tcp -m tcp --dport 2802 -j ACCEPT
-A OUTPUT -p tcp -m tcp --dport 8080 -j ACCEPT
-A OUTPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
-A OUTPUT -p tcp -m tcp --dport 21 -j ACCEPT
-A OUTPUT -p tcp -m tcp --dport 23 -j ACCEPT
COMMIT
# Completed on Wed Jan 17 10:35:18 2007
# Generated by iptables-save v1.3.0 on Wed Jan 17 10:35:18 2007
*nat
:OUTPUT ACCEPT [9:8239]
:POSTROUTING ACCEPT [2:245]
:PREROUTING ACCEPT [53:5377]
-A POSTROUTING -s 192.168.0.0/255.255.255.0 -o eth2 -j SNAT --to-source
202.21.179.2
COMMIT
# Completed on Wed Jan 17 10:35:18 2007

and here is the code I wrote:

#!/usr/bin/perl -w

use strict ;

my $file = iptables.bac ;
my @sorted_list ;
my %barrel ;
my $item = 0 ;

open IPTABLES, $file
   or die Could not open '$file': $!\n ;
my @content = IPTABLES ;

foreach (@content) {
   if (/.*-A MAC/) {
   my @chunks = split ;
   my $last_octet = $chunks[3] ;
   $last_octet =~ s/^.*\.// ;
   $barrel{$last_octet} = $_ ;
   }
}

foreach (sort { $a = $b } keys %barrel) {
   push @sorted_list, $barrel{$_} ;
}

foreach (@content) {
   s/.*-A MAC.*\n$// ;
}

print @content ;

Can someone please help me...Thank you in advance...!

--
Typos
FourThirty Inc.
Domain Administrator


Re: How to insert an array in to the middle of another array after a certain pattern

2007-04-13 Thread John W. Krahn
Typos wrote:
 Hello everyone,

Hello,

 I'm a Perl beginner and I've been trying for a while to to insert an array
 in to the middle of another array

perldoc -f splice

 after a certain pattern.

More difficult.  You first have to determine at what array index the pattern
exists.

 Here is what I'm trying to do...I have the Linux Iptables configuration
 file,

A file is not an array, unless you use the Tie::File module.

 which has a custom chain called MAC which hold all the IP to MAC
 entries mappings. Since I update the list manually, I usually end up
 with IP addresses here and there...I managed to put all the sorted
 IP to MAC entries on a seperate array, and then remove all the MAC
 entries from the original file...So what I basically need to do is
 insert the sorted iptables array between the INPUT and OUTPUT
 chains. Here is a sample output of the array, when all MAC entries
 are removed...

When all MAC entries are in the file are they all grouped together like the
FORWARD, INPUT and OUTPUT entries?  Where do you get the sorted iptables
array from?

Perhaps something like this (UNTESTED):

while ( FILE ) {
if ( ?^-A OUTPUT? ) {
print @sorted_iptables;
}
print;
}




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/




Re: postgres insert

2006-11-25 Thread Tom Allison

D. Bolliger wrote:

Tom Allison am Donnerstag, 23. November 2006 16:13:

[snipped some code]

I get a STDERR warning printed out everytime this has a duplicate key
violation...

Any idea why eval{} doesn't suppress this?


Hi Tom

It'd be a bad idea... eval BLOCK adds the ability to catch runtime errors and 
modify the default reaction to a die. It is not here to hide any problems of 
code.




Found out what the problem was.  I had PrintError enabled by default.
Once that was set to PrintError = 0 the problem went away.

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




postgres insert

2006-11-23 Thread Tom Allison

I've been using something like this for Oracle for some time
and tried it with Postgresql.

(RaiseError doesn't change the outcome)


  sub insert_token {
my $token = shift;
eval{ $sth1-execute($token) };
if ($@) {
  return 1 if $@ =~ /duplicate key violates unique constraint/;
  die ERROR: [EMAIL PROTECTED];
}
return $sth1-rows;
  }



I get a STDERR warning printed out everytime this has a duplicate key 
violation...

Any idea why eval{} doesn't suppress this?

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




Re: postgres insert

2006-11-23 Thread D. Bolliger
Tom Allison am Donnerstag, 23. November 2006 16:13:

[snipped some code]
 I get a STDERR warning printed out everytime this has a duplicate key
 violation...

 Any idea why eval{} doesn't suppress this?

Hi Tom

It'd be a bad idea... eval BLOCK adds the ability to catch runtime errors and 
modify the default reaction to a die. It is not here to hide any problems of 
code.

You can suppress the output of warnings at a certain place by f.ex:

#!/usr/bin/perl

use strict; use warnings;

warn Test1\n;
{
  local $SIG{__WARN__}=sub {}; # 
  warn Test2\n;
}
warn Test3\n;

__END__

output:

Test1
Test3

Dani [not part of the output...]

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




Insert value in existing record

2006-05-18 Thread Gerald Wheeler
Wondering how I can insert a value: abc| w/o the quotes) immediately
after the third | (pipe character) in file xyz.txt. Each record within
the file has 14 fields separated by the pipe character.
Example:
Before:
  
one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|thirteen|fourteen|

  
one|two|three|added|five|six|seven|eight|nine|ten|eleven|twelve|thirteen|fourteen|fifteen|

 Thanks;;

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




Re: Insert value in existing record

2006-05-18 Thread Tom Phoenix

On 5/18/06, Gerald Wheeler [EMAIL PROTECTED] wrote:


Wondering how I can insert a value: abc| w/o the quotes) immediately
after the third | (pipe character) in file xyz.txt.


There's more than one way to do it. One way would be a substitution
(s///). Another would be to use split and join: split the line, do
whatever you need to do with the elements, then join the pieces. Would
that work for you?

--Tom Phoenix
Stonehenge Perl Training

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




RE: Insert value in existing record

2006-05-18 Thread Saboo, Nandakishore
Hi,

As Tom Phoenix said there are many ways to do it, this is one of the way we can 
do it.

+++
$string = 
one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|thirteen|fourteen|;
$added = abc|;

@tmp_array = split(/\|/,$string,4);

for ($i=0;$i$#tmp_array;$i++)
{
$tmp .= $tmp_array[$i].|;
}

$tmp .= $added ;
$tmp .= $tmp_array[$#tmp_array] ;
print $tmp,\n;
+++

Thanks,
nandakishore saboo.
[ Forgive me if i am wrong(still a learner) ]







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




Re: Insert value in existing record

2006-05-18 Thread John W. Krahn
Saboo, Nandakishore wrote:
 Hi,

Hello,

 As Tom Phoenix said there are many ways to do it, this is one of the way we 
 can do it.
 
 +++
 $string = 
 one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|thirteen|fourteen|;
 $added = abc|;
 
 @tmp_array = split(/\|/,$string,4);
 
 for ($i=0;$i$#tmp_array;$i++)
 {
 $tmp .= $tmp_array[$i].|;
 }
 
 $tmp .= $added ;
 $tmp .= $tmp_array[$#tmp_array] ;
 print $tmp,\n;

It would be easier to use splice:

$string =
'one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|thirteen|fourteen|';
$added = 'abc';

@tmp_array = split /\|/, $string, 4;
splice @tmp_array, 3, 0, $added;

print join '|', @tmp_array;




John
-- 
use Perl;
program
fulfillment

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




mysql insert errors

2006-04-07 Thread Practical Perl
Hello,all,

I wrote a script to insert datas to mysql database.The insert frequency is
about 45 times per second.
Most of the insert actions are successful,but I still see some errors as
follow:

DBD::mysql::st execute failed: INSERT command denied to user
'abc'@'192.168.3.10' for table 'rcpt' at ./rcptsvr line 377

Could anyone tell me why this error happened with my Perl script?Thanks.


Re: mysql insert errors

2006-04-07 Thread Chas Owens
On 4/7/06, Practical Perl [EMAIL PROTECTED] wrote:
 Hello,all,

 I wrote a script to insert datas to mysql database.The insert frequency is
 about 45 times per second.
 Most of the insert actions are successful,but I still see some errors as
 follow:

 DBD::mysql::st execute failed: INSERT command denied to user
 'abc'@'192.168.3.10' for table 'rcpt' at ./rcptsvr line 377

 Could anyone tell me why this error happened with my Perl script?Thanks.

If you are running MySQL 4.0 on MS Windows then this might be your problem

http://bugs.mysql.com/bug.php?id=5569

I found a couple other mentions of similar issues (mostly around MySQL
on MS Windows) in a quick google search.  Can you reproduce the error
consistently?  If so you might consider filing a bug on
bugs.mysql.com.

All in all it sounds like a database bug rather than a Perl bug, but a
work around might be something like this (assuming you have RaiseError
= 1 in your connect)

my $sth = $dbh-prepare(insert into rcpt values (?, ?, ?, ?))
my $tries = 5;
for my $data (get_data()) {
for ( 1 .. $tries) {
eval { $sth-execute(@$data) };

# exit retry loop if successful
unless ($@) {
$tries = 0;
break;
}

#die if any error other than denied
die $@ unless $@ =~ /INSERT command denied to user/;
}
if ($tries) {
die
Insert failed due to permission issue, tried $tries times\n .
Data was: @$data;
}
}

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




Re: mysql insert errors

2006-04-07 Thread Dr.Ruud
Practical Perl schreef:

 I wrote a script to insert datas to mysql database.The insert
 frequency is about 45 times per second.
 Most of the insert actions are successful,but I still see some errors
 as follow:
 
 DBD::mysql::st execute failed: INSERT command denied to user
 'abc'@'192.168.3.10' for table 'rcpt' at ./rcptsvr line 377
 
 Could anyone tell me why this error happened with my Perl
 script?

Most probably not Perl-related. 

A quick 

  google: mysql insert command denied 

will find many like
  http://bugs.mysql.com/bug.php?id=5569 

-- 
Affijn, Ruud

Gewoon is een tijger.

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




Re: mysql insert errors

2006-04-07 Thread Practical Perl
Thanks for all,I'll try some ways to fit it.


DBI insert vs update question

2005-07-10 Thread Peter Rabbitson
Hello everyone,
I want someone to share his expertise on the following:
Suppose we have a table with some data that periodically must be synced 
with an external source, which provides only partial information (e.g. 
it might provide all the fields for a new record, but might provide 
only a single field difference for an already existing record). This 
obviously will involve a series of UPDATE and INSERT statements, mostly 
in random order. As most RDBMS can hold only one prepared statement at a 
time (including MySQL) I have 2 ways to do this that look somewhat 
efficient:

1. Sweep the pre-existing table into a hash, DELETE all the records from 
it and INSERT the new data, using the hash as a source for missing 
fields.

2. Create 3 connections to the database, have the first one hold a 
SELECT statement that will replace the hash above, have the second 
connection be an INSERT for nonexisting records and the third connection 
be an UPDATE for existing ones

From reading on DBI I understood that moving lots of data with do()
statements is pretty slow (e.g. constantly re-preparing the same 
statement), so I think scenario 2 with a single connection is even 
worse.

The reason I am elaborating on this is that I am afraid the dataset will 
stop fitting in memory at some point of time if I go with scenario 1 
(which is easier and cleaner to implement). Also I have no idea how 
resource intensive scenario 2 would be, although I have proper 
indexing and stuff so the UPDATES should be fast enough...

Thanks

Peter

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




Re: DBI insert vs update question

2005-07-10 Thread Octavian Rasnita
Can't you use the replace sql query?

Use it like you use insert. It will insert new rows where there are no
rows, and do an update where there are rows...

Teddy


- Original Message - 
From: Peter Rabbitson [EMAIL PROTECTED]
To: beginners@perl.org
Sent: Sunday, July 10, 2005 18:09 PM
Subject: DBI insert vs update question


 Hello everyone,
 I want someone to share his expertise on the following:
 Suppose we have a table with some data that periodically must be synced
 with an external source, which provides only partial information (e.g.
 it might provide all the fields for a new record, but might provide
 only a single field difference for an already existing record). This
 obviously will involve a series of UPDATE and INSERT statements, mostly
 in random order. As most RDBMS can hold only one prepared statement at a
 time (including MySQL) I have 2 ways to do this that look somewhat
 efficient:

 1. Sweep the pre-existing table into a hash, DELETE all the records from
 it and INSERT the new data, using the hash as a source for missing
 fields.

 2. Create 3 connections to the database, have the first one hold a
 SELECT statement that will replace the hash above, have the second
 connection be an INSERT for nonexisting records and the third connection
 be an UPDATE for existing ones

 From reading on DBI I understood that moving lots of data with do()
 statements is pretty slow (e.g. constantly re-preparing the same
 statement), so I think scenario 2 with a single connection is even
 worse.

 The reason I am elaborating on this is that I am afraid the dataset will
 stop fitting in memory at some point of time if I go with scenario 1
 (which is easier and cleaner to implement). Also I have no idea how
 resource intensive scenario 2 would be, although I have proper
 indexing and stuff so the UPDATES should be fast enough...

 Thanks

 Peter

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




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




Re: DBI insert vs update question

2005-07-10 Thread Peter Rabbitson
On Sun, Jul 10, 2005 at 06:23:19PM +0300, Octavian Rasnita wrote:
 Can't you use the replace sql query?
 
 Use it like you use insert. It will insert new rows where there are no
 rows, and do an update where there are rows...
 

Negative. REPLACE is just a shortcut for DELETE FROM... INESERT INTO (at 
least in MySQL) with some pretty neat gimmicks to find out what exactly 
to DELETE. Performance is the same but you have less control.

Peter

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




Re: DBI insert vs update question

2005-07-10 Thread Peter Rabbitson
 I'm sure others will give you more informed answers..  But why can't
 you create multiple statement handlers under the same connection?
 

Because you can't. One connection holds only one prepared statement (at 
least in MySQL). If you prepare $statement2 on the same $dbh, 
$statement1 automatically gets invalidated. Clinically proven :)

Peter


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




Re: DBI insert vs update question

2005-07-10 Thread Mads N. Vestergaard

-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

Hey Peter,

Are you sure about that?
As far as I understand, what you say you can't do, is to have two
prepares  for example:

my $dbh = DBI-connect(dbi:mysql:database,user,pass);
my $foo = $dbh-prepare(SELECT * FROM .);
my $bar = $dbh-prepare(INSERT INTO .);
$foo-execute();
$foo-finish();
$bar-execute();
$bar-finish();

At least that works for me.

Sorry if I misunderstood you.


Mads

Peter Rabbitson wrote:
|I'm sure others will give you more informed answers..  But why can't
|you create multiple statement handlers under the same connection?
|
|
|
| Because you can't. One connection holds only one prepared statement (at
| least in MySQL). If you prepare $statement2 on the same $dbh,
| $statement1 automatically gets invalidated. Clinically proven :)
|
| Peter
|
|

- --
Mads N. Vestergaard - http://rwxr-xr-x.dk
Interested in Open Source, and web application development
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.1 (GNU/Linux)

iD8DBQFC0Ukt7WOaPMd53OMRAvcCAJ0Y/kCn1Oh67D3AUrCfpq7ihBOu8QCeO/SC
JMvYjVK+8naZfgReXn13AQU=
=psBJ
-END PGP SIGNATURE-

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




Re: DBI insert vs update question

2005-07-10 Thread David Van Ginneken
Below is taken from: http://search.cpan.org/dist/DBD-mysql/lib/DBD/mysql.pm

Also look at: 
http://dev.mysql.com/tech-resources/articles/4.1/prepared-statements.html


Prepared statement support (server side prepare)

To use server side prepared statements, all you need to do is set
the variable mysql_server_prepare in the connect:

$dbh = DBI-connect(
DBI:mysql:database=test;host=localhost:mysql_server_prepare=1, ,
, { RaiseError = 1, AutoCommit = 1 } );

To make sure that the 'make test' step tests whether server
prepare works, you just need to export the env variable
MYSQL_SERVER_PREPARE:

export MYSQL_SERVER_PREPARE=1

Test first without server side prepare, then with.


On 7/10/05, Mads N. Vestergaard [EMAIL PROTECTED] wrote:
 -BEGIN PGP SIGNED MESSAGE-
 Hash: SHA1
 
 Hey Peter,
 
 Are you sure about that?
 As far as I understand, what you say you can't do, is to have two
 prepares  for example:
 
 my $dbh = DBI-connect(dbi:mysql:database,user,pass);
 my $foo = $dbh-prepare(SELECT * FROM .);
 my $bar = $dbh-prepare(INSERT INTO .);
 $foo-execute();
 $foo-finish();
 $bar-execute();
 $bar-finish();
 
 At least that works for me.
 
 Sorry if I misunderstood you.
 
 
 Mads
 
 Peter Rabbitson wrote:
 |I'm sure others will give you more informed answers..  But why can't
 |you create multiple statement handlers under the same connection?
 |
 |
 |
 | Because you can't. One connection holds only one prepared statement (at
 | least in MySQL). If you prepare $statement2 on the same $dbh,
 | $statement1 automatically gets invalidated. Clinically proven :)
 |
 | Peter
 |
 |
 
 - --
 Mads N. Vestergaard - http://rwxr-xr-x.dk
 Interested in Open Source, and web application development
 -BEGIN PGP SIGNATURE-
 Version: GnuPG v1.4.1 (GNU/Linux)
 
 iD8DBQFC0Ukt7WOaPMd53OMRAvcCAJ0Y/kCn1Oh67D3AUrCfpq7ihBOu8QCeO/SC
 JMvYjVK+8naZfgReXn13AQU=
 =psBJ
 -END PGP SIGNATURE-
 
 --
 To unsubscribe, e-mail: [EMAIL PROTECTED]
 For additional commands, e-mail: [EMAIL PROTECTED]
 http://learn.perl.org/ http://learn.perl.org/first-response
 
 


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




Re: DBI insert vs update question

2005-07-10 Thread Wiggins d'Anconia
Peter Rabbitson wrote:
 Hello everyone,
 I want someone to share his expertise on the following:
 Suppose we have a table with some data that periodically must be synced 
 with an external source, which provides only partial information (e.g. 
 it might provide all the fields for a new record, but might provide 
 only a single field difference for an already existing record). This 
 obviously will involve a series of UPDATE and INSERT statements, mostly 
 in random order. As most RDBMS can hold only one prepared statement at a 
 time (including MySQL) I have 2 ways to do this that look somewhat 
 efficient:


What version of MySQL? Generally this would be handled with a
transaction, but only newer MySQLs support them. And I suspect Randal
(if he is listening) will pop in with a comment about using PostgreSQL
right about now :-). And now, having used both I would agree with him.

 1. Sweep the pre-existing table into a hash, DELETE all the records from 
 it and INSERT the new data, using the hash as a source for missing 
 fields.
 

Yeh this sounds like a nightmare.

 2. Create 3 connections to the database, have the first one hold a 
 SELECT statement that will replace the hash above, have the second 
 connection be an INSERT for nonexisting records and the third connection 
 be an UPDATE for existing ones
 

As the other posters said, and to my knowledge, you should double check
that you can't prepare multiple statements.  From the DBI docs:

http://search.cpan.org/~timb/DBI-1.48/DBI.pm#prepare

Portable applications should not assume that a new statement can be
prepared and/or executed while still fetching results from a previous
statement.

That is a should not assume rather than a can't do it, and that is
specifically geared towards portable applications which generally
means when dealing with multiple different db backends. You might also
want to have a read through the 'prepare_cached' section following the
above. It appears to be a way in DBI to handle the same if the backend
doesn't support it.

From reading on DBI I understood that moving lots of data with do()
 statements is pretty slow (e.g. constantly re-preparing the same 
 statement), so I think scenario 2 with a single connection is even 
 worse.
 

Slow is still only meaningful in your context until you benchmark
whether it really is too slow you won't know.

 The reason I am elaborating on this is that I am afraid the dataset will 
 stop fitting in memory at some point of time if I go with scenario 1 
 (which is easier and cleaner to implement). Also I have no idea how 
 resource intensive scenario 2 would be, although I have proper 
 indexing and stuff so the UPDATES should be fast enough...


Easier I would agree with, cleaner I definitely wouldn't, at least not
if we are talking about enterprise level stuff. There are all kinds of
issues you can run into when trying to do a DELETE/INSERT instead of the
more appropriate UPDATE, especially when there is an intermediary (your
Perl hash) involved.

 Thanks
 
 Peter
 

HTH some,

http://danconia.org

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




using Perl to insert footer into PDF files?

2005-03-29 Thread Alex Walker
I'm a little new at PDF manipulation in Perl and I'm
not completely convinced that what I want to do is
even possible. Basically what i want to do is take a
multi-page PDF file and insert a footer onto the
bottom of every page along with sequential page
numbers. I've been tinkering with the PDF::API2
module, which looks promising but which appears to be
a little slim on documentation. Can someone point me
in the right direction on this?

Thanks a lot,
Alex



__ 
Do you Yahoo!? 
Yahoo! Mail - Easier than ever with enhanced search. Learn more. 
http://info.mail.yahoo.com/mail_250

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




How to track the success of insert

2004-09-29 Thread Anish Kumar K.
Hi

I was trying out some practice examples with DBI and CGI and kind of stuck while doing 
a comparison

That is if I  could insert successfully into a databse a script window shld come 
Success. but when the insert fails 
a window shld come saying Can;t insert ..

How will I track if the insertion is success or not? Below is the program...


use strict;
use warnings;
use CGI;
use DBI;
my $cgi = new CGI;
print $cgi-header( text/html );
print $cgi-start_html( Welcome );
my $dbh = 
DBI-connect(DBI:Pg:dbname=testdb;host=localhost,'postgres','postgres',{RaiseError=1,PrintErr
or=1})
or die Cannot connect to testdb\n;

my $sth=$dbh-prepare(insert into userinfo values('$fvalue','$lvalue','$email'));
$sth-execute();
   if($sth)
{
   print $cgi-p( script language=Javascript alert('Execution Done') /script 
);
}
 else
   {
   print $cgi-p(Script language=Javascript alert('Execution Not Done') 
/script );
   }


RE: How to track the success of insert

2004-09-29 Thread NYIMI Jose \(BMB\)


 -Original Message-
 From: Anish Kumar K. [mailto:[EMAIL PROTECTED] 
 Sent: Wednesday, September 29, 2004 9:28 AM
 To: beginners perl
 Subject: How to track the success of insert
 
 
 Hi
 
 I was trying out some practice examples with DBI and CGI and 
 kind of stuck while doing a comparison
 
 That is if I  could insert successfully into a databse a 
 script window shld come Success. but when the insert fails 
 a window shld come saying Can;t insert ..
 
 How will I track if the insertion is success or not? Below is 
 the program...
 
 
 use strict;
 use warnings;
 use CGI;
 use DBI;
 my $cgi = new CGI;
 print $cgi-header( text/html );
 print $cgi-start_html( Welcome );
 my $dbh = 
 DBI-connect(DBI:Pg:dbname=testdb;host=localhost,'postgres',
 'postgres',{RaiseError=1,PrintErr
 or=1})
 or die Cannot connect to testdb\n;
 
 my $sth=$dbh-prepare(insert into userinfo 
 values('$fvalue','$lvalue','$email'));
 $sth-execute();
if($sth)
 {
print $cgi-p( script language=Javascript 
 alert('Execution Done') /script );
 }
  else
{
print $cgi-p(Script language=Javascript 
 alert('Execution Not Done') /script );
}

Suggestion:
Put your instert inside a transaction like this:

[snip]

#begin transaction
$dbh-begin_work;
eval{   
#you can decide to combine prepare() and execute() into do()
$dbh-do( insert into userinfo values ('$fvalue','$lvalue','$email') );
};
#check if the transaction went ok
if($@){ 
$dbh-rollback;
print $cgi-p(Script language=Javascript alert('Execution Not Done') 
/script );
}
else{
$dbh-commit;
print $cgi-p( script language=Javascript alert('Execution Done') 
/script );  
}


Tim Bunce (the Auteur of DBI) gave a nice presentation about
DBI transactions that you can find from this link:
http://search.cpan.org/src/TIMB/DBI_AdvancedTalk_2004/sld054.htm

Or from
http://dbi.perl.org (Online Documentation)

HTH,

José.



 DISCLAIMER 

This e-mail and any attachment thereto may contain information which is confidential 
and/or protected by intellectual property rights and are intended for the sole use of 
the recipient(s) named above. 
Any use of the information contained herein (including, but not limited to, total or 
partial reproduction, communication or distribution in any form) by other persons than 
the designated recipient(s) is prohibited. 
If you have received this e-mail in error, please notify the sender either by 
telephone or by e-mail and delete the material from any computer.

Thank you for your cooperation.

For further information about Proximus mobile phone services please see our website at 
http://www.proximus.be or refer to any Proximus agent.


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




RE: How to track the success of insert

2004-09-29 Thread NYIMI Jose \(BMB\)


 -Original Message-
 From: Anish Kumar K. [mailto:[EMAIL PROTECTED]
 Sent: Wednesday, September 29, 2004 9:28 AM
 To: beginners perl
 Subject: How to track the success of insert
 
 
 Hi
 
 I was trying out some practice examples with DBI and CGI and
 kind of stuck while doing a comparison
 
 That is if I  could insert successfully into a databse a
 script window shld come Success. but when the insert fails 
 a window shld come saying Can;t insert ..
 
 How will I track if the insertion is success or not? Below is
 the program...
 
 
 use strict;
 use warnings;
 use CGI;
 use DBI;
 my $cgi = new CGI;
 print $cgi-header( text/html );
 print $cgi-start_html( Welcome );
 my $dbh =
 DBI-connect(DBI:Pg:dbname=testdb;host=localhost,'postgres',
 'postgres',{RaiseError=1,PrintErr
 or=1})
 or die Cannot connect to testdb\n;
 
 my $sth=$dbh-prepare(insert into userinfo
 values('$fvalue','$lvalue','$email'));
 $sth-execute();
if($sth)
 {
print $cgi-p( script language=Javascript 
 alert('Execution Done') /script );
 }
  else
{
print $cgi-p(Script language=Javascript 
 alert('Execution Not Done') /script );
}

Suggestion:
Put your instert inside a transaction like this:

[snip]

#begin transaction
$dbh-begin_work;
eval{   
#you can decide to combine prepare() and execute() into do()
$dbh-do( insert into userinfo values ('$fvalue','$lvalue','$email') );
$dbh-commit;
};
#check if the transaction went ok
if($@){ 
$dbh-rollback;
print $cgi-p(Script language=Javascript alert('Execution Not Done') 
/script );
}
else{
print $cgi-p( script language=Javascript alert('Execution Done') 
/script );  
}


Tim Bunce (the Author of DBI) gave a nice presentation
about DBI transactions that you can find from this link:
http://search.cpan.org/src/TIMB/DBI_AdvancedTalk_2004/sld054.htm

Or from
http://dbi.perl.org (Online Documentation)

HTH,

José.



 DISCLAIMER 

This e-mail and any attachment thereto may contain information which is confidential 
and/or protected by intellectual property rights and are intended for the sole use of 
the recipient(s) named above. 
Any use of the information contained herein (including, but not limited to, total or 
partial reproduction, communication or distribution in any form) by other persons than 
the designated recipient(s) is prohibited. 
If you have received this e-mail in error, please notify the sender either by 
telephone or by e-mail and delete the material from any computer.

Thank you for your cooperation.

For further information about Proximus mobile phone services please see our website at 
http://www.proximus.be or refer to any Proximus agent.


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



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




RE: insert data with Perl into multiple MySQL tables

2004-09-17 Thread Bob Showalter
Maxipoint Rep Office wrote:
 How insert data with Perl into multiple MySQL tables?

You need multiple INSERT statements. Use a transaction if they all need to
complete or fail together. I don't use MySQL, so I don't know how
transactions work for it specifically, but typically you just use a
combination of $dbh-{AutoCommit} and $dbh-commit.

 
 I can not find any clear advice..
 
 
 this is for TABLE1:
 
 # Connect to the database.
 my $dbh = DBI-connect(DBI:mysql:database=;host=localhost,
username, pass,
{'RaiseError' = 1});
 
 
 # now first make that sql statement the right way - use placeholders
 
 my $sql = INSERT INTO TABLE1 (xxx1, xxx2, xxx3) VALUES (?,?,?);
 
 
 #now prepare it
 my $sth = $dbh-prepare($sql);
 
 
 # now simply execute it
 
 $sth-execute($f-{xxx1},$f-{xxx2},$f-{xxx3});
 
 
 $sth-finish();

finish() is only needed for statements that return rows.

Also the prepare/execute can all be simplified to

$dbh-do(q[
insert into table1 (xxx1, xxx2, xxx3) values (?, ?, ?)
], undef, @{$f}{qw(xxx1 xxx2 xxx3)});

Using prepare separately is handy if you need to repeat the insert multiple
times for different data; otherwise, using $dbh-do is usually simpler.

 
 $dbh-disconnect();
 
 
 
 How insert into TABLE1 and TABLE2 at same time?

You need to prepare/execute (or $dbh-do) another statement for that.

   $dbh-do(q[insert into table2 ...blah blah], undef, @params);

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




insert data with Perl into multiple MySQL tables

2004-09-16 Thread Maxipoint Rep Office
How insert data with Perl into multiple MySQL tables?

I can not find any clear advice..


this is for TABLE1:

# Connect to the database.
my $dbh = DBI-connect(DBI:mysql:database=;host=localhost,
   username, pass,
   {'RaiseError' = 1});


# now first make that sql statement the right way - use placeholders

my $sql = INSERT INTO TABLE1 (xxx1, xxx2, xxx3) VALUES (?,?,?); 


#now prepare it
my $sth = $dbh-prepare($sql);


# now simply execute it

$sth-execute($f-{xxx1},$f-{xxx2},$f-{xxx3});


$sth-finish();

$dbh-disconnect();



How insert into TABLE1 and TABLE2 at same time?

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




RE: create connection from html form into insert MySQL data script

2004-09-08 Thread Maxipoint Rep Office


-Original Message-
From: Eduardo Vázquez Rodríguez [mailto:[EMAIL PROTECTED]
Sent: Wednesday, September 08, 2004 2:02 AM
To: Maxipoint Rep Office
Cc: Charles K. Clarkson; [EMAIL PROTECTED]
Subject: Re: create connection from html form into insert MySQL data script


I think he is from Croatia. moreover in the last part of  this message I
think what he is pretending is to accomplish a better way of inserting
into the database.
I think that one of his goals is to avoid the use of the variable names
when inserting I believe that he pretends to catch the values of the
CGI.pm and : HTML::template and using that values for inserting into the
database instead of using names like

my $turistobjekt = dadas;
my $adresa = sdasdasdfADRESA;
my $brojgrada = 1;

RE: yes, you are describe exactly what I want?
and any help here finaly?

-GP




Maxipoint Rep Office wrote:

-Original Message-
From: Charles K. Clarkson [mailto:[EMAIL PROTECTED]
Sent: Wednesday, September 08, 2004 1:06 AM
To: 'Maxipoint Rep Office'; [EMAIL PROTECTED]
Subject: RE: create connection from html form into insert MySQL data script


Maxipoint Rep Office [EMAIL PROTECTED] wrote:

: I am successful insert data in MySQL with code below:

   I am having trouble understanding your message. I assume
English is not your first language.

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

Great start!
RE: yeah.. :-)



: use DBI();
: use CGI;
: use HTML::Template;
:
: # Connect to the database.
: my $dbh =
: DBI-connect(DBI:mysql:database=MYDABASE;host=localhost,
: MYDBUSERNAME, MYPASS,
: {'RaiseError' = 1});
:
: my $turistobjekt = dadas;
: my $adresa = sdasdasdfADRESA;
: my $brojgrada = 1;
: my $grad = 1;
: my $manjemjesto = 1;
: my $otok = 1;
: my $regija = 1;
: my $ime = 1;
: my $prezime = 1;
: my $tel = 1;
: my $mob = 1;
: my $fax = 1;
: my $email = 1;
: my $username = 1;
: my $password = 1;
: my $status = 1;

Are all these variables supposed to be coming from
an HTML form? Is that what you want to use CGI.pm for?
RE: yes, I wish delete it in script and that form send same values using
CGI.pm and HTMP::template



: $dbh-do(INSERT INTO portal (turistobjekt, adresa, brojgrada,
: grad, manjemjesto, otok, regija, ime, prezime, tel, mob, fax,
: email, username,
: password, status) VALUES ('$turistobjekt', '$adresa',
: '$brojgrada', '$grad', '$manjemjesto', '$otok', '$regija',
: '$ime', '$prezime', '$tel', '$mob', '$fax', '$email',
: '$username', '$password', '$status') or die $dbh-errstr);
:
: $dbh-disconnect();
:
: 
:
:
: MY QUESTION: How on much simpler way with CGI.pm and
: HTML::template, instead variables my $turistobjekt, my
: $adresa, my $brojgrada etc. RECEIVE any data from html form
: successful?

HTML::Template is used to generate HTML pages. You are
not doing that here. What task are you trying to accomplish,
(besides the DB insert)?
RE: ok, I can resolve HTML::template alone later, can you help me with
CGI.pm... how send data into inerst script from form? not with variables
like I am create here?

-GP






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



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




RE: create connection from html form into insert MySQL data script

2004-09-08 Thread Charles K. Clarkson
Maxipoint Rep Office [EMAIL PROTECTED] wrote:
: 
: Charles [mailto:[EMAIL PROTECTED] wrote:
: : 
: : Maxipoint Rep Office [EMAIL PROTECTED] wrote:
: : 
: :
: : : my $turistobjekt = dadas;
: : : my $adresa = sdasdasdfADRESA;
: : : my $brojgrada = 1;
: : : my $grad = 1;
: : : my $manjemjesto = 1;
: : : my $otok = 1;
: : : my $regija = 1;
: : : my $ime = 1;
: : : my $prezime = 1;
: : : my $tel = 1;
: : : my $mob = 1;
: : : my $fax = 1;
: : : my $email = 1;
: : : my $username = 1;
: : : my $password = 1;
: : : my $status = 1;
: : 
: : Are all these variables supposed to be coming from
: : an HTML form? Is that what you want to use CGI.pm for?
:
: RE: yes, I wish delete it in script and that form send same
: values using CGI.pm and HTMP::template

[snip]

: : : $dbh-do(INSERT INTO portal (turistobjekt, adresa, brojgrada,
: : : grad, manjemjesto, otok, regija, ime, prezime, tel, mob, fax,
: : : email, username, password, status) VALUES ('$turistobjekt',
: : : '$adresa', '$brojgrada', '$grad', '$manjemjesto', '$otok',
: : : '$regija', '$ime', '$prezime', '$tel', '$mob', '$fax',
: : : '$email', '$username', '$password', '$status') or die
: : : $dbh-errstr); 

 Let's change this to something a bit more readable. Like
this we can see the order needed and a shortcut to building
the INSERT.

INSERT INTO portal (
turistobjekt,
adresa,
brojgrada,
grad,
manjemjesto,
otok,
regija,
ime,
prezime,
tel,
mob,
fax,
email,
username,
password,
status
)
VALUES (
'$turistobjekt',
'$adresa',
'$brojgrada',
'$grad',
'$manjemjesto',
'$otok',
'$regija',
'$ime',
'$prezime',
'$tel',
'$mob',
'$fax',
'$email',
'$username',
'$password',
'$status'
)


I'm not a DB expert, but the module does mention that
INSERTs should be of the this form. The question (?) marks are
place holders.

INSERT INTO sales (id, qty, price) VALUES (?, ?, ?)

The module also shows the form of a do() with place
holders. We'll model our do() on the same form. Since we don't
have %attr we will use 'undef'.

$dbh-do($statement, \%attr, @bind_values);


We need to end up with this. But we need to be certain we
can easily adjust our fields in the future.

INSERT INTO portal (
turistobjekt,
adresa,
brojgrada,
grad,
manjemjesto,
otok,
regija,
ime,
prezime,
tel,
mob,
fax,
email,
username,
password,
status
)
VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )


To do that we need only know the order and names of those
fields. An array would probably be best.

my @ordered_fields = qw(
turistobjektadresa  brojgrada   gradmanjemjesto
otokregija  ime prezime tel
mob fax email   username
passwordstatus
);

We will need the Portal fields.

my $portal =
'portal (' .
join( ',', @ordered_fields ) .
')';

And the place holders.

my $place_holders =
'(' .
join( ',', ('?') x @ordered_fields ) .
')';

An INSERT.

my $insert = qq(INSERT INTO $portal VALUES $place_holders);

Finally we need an ordered list of fields from the form.

my $q   = CGI-new();
my %params  = $q-Vars;

@params{ @ordered_fields }

Now, we put it all together. (This is not tested.)

my $q   = CGI-new();
my %params  = $q-Vars();

my @ordered_fields = qw(
turistobjektadresa  brojgrada   gradmanjemjesto
otokregija  ime prezime tel
mob fax email   username
passwordstatus
);

my $portal =
'portal (' .
join( ',', @ordered_fields ) .
')';

my $place_holders =
'(' .
join( ',', ('?') x @ordered_fields ) .
')';

my $insert = qq(INSERT INTO $portal VALUES $place_holders);

my $return_value =
$dbh-do( $insert, undef, @params{ @ordered_fields } );


Should we need to change the order or names of fields
in the future, we need only change the form and
@ordered_fields.



HTH,

Charles K. Clarkson
-- 
Mobile Homes Specialist
254 968-8328



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




create connection from html form into insert MySQL data script

2004-09-07 Thread Maxipoint Rep Office


I am successful insert data in MySQL with code below:


#!/usr/bin/perl -w
use strict;
use DBI();
use CGI;
use HTML::Template;


# Connect to the database.
my $dbh = DBI-connect(DBI:mysql:database=MYDABASE;host=localhost,
   MYDBUSERNAME, MYPASS,
   {'RaiseError' = 1});

my $turistobjekt = dadas;
my $adresa = sdasdasdfADRESA;
my $brojgrada = 1;
my $grad = 1;
my $manjemjesto = 1;
my $otok = 1;
my $regija = 1;
my $ime = 1;
my $prezime = 1;
my $tel = 1;
my $mob = 1;
my $fax = 1;
my $email = 1;
my $username = 1;
my $password = 1;
my $status = 1;


$dbh-do(INSERT INTO portal (turistobjekt, adresa, brojgrada, grad,
manjemjesto, otok, regija, ime, prezime, tel, mob, fax, email, username,
password, status) VALUES ('$turistobjekt', '$adresa', '$brojgrada', '$grad',
'$manjemjesto', '$otok', '$regija', '$ime', '$prezime', '$tel', '$mob',
'$fax', '$email', '$username', '$password', '$status') or die
$dbh-errstr);



$dbh-disconnect();




MY QUESTION: How on much simpler way with CGI.pm and HTML::template, instead
variables my $turistobjekt , my $adresa, my $brojgrada etc. RECEIVE any data
from html form successful?

I am read documentation, but whole day have errors.. can someone add and
explain own code connected with my above insert data script..






















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




RE: create connection from html form into insert MySQL data script

2004-09-07 Thread Charles K. Clarkson
Maxipoint Rep Office [EMAIL PROTECTED] wrote:

: I am successful insert data in MySQL with code below:

   I am having trouble understanding your message. I assume
English is not your first language.

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

Great start!


: use DBI();
: use CGI;
: use HTML::Template;
: 
: # Connect to the database.
: my $dbh =
: DBI-connect(DBI:mysql:database=MYDABASE;host=localhost,
: MYDBUSERNAME, MYPASS,
: {'RaiseError' = 1});
: 
: my $turistobjekt = dadas;
: my $adresa = sdasdasdfADRESA;
: my $brojgrada = 1;
: my $grad = 1;
: my $manjemjesto = 1;
: my $otok = 1;
: my $regija = 1;
: my $ime = 1;
: my $prezime = 1;
: my $tel = 1;
: my $mob = 1;
: my $fax = 1;
: my $email = 1;
: my $username = 1;
: my $password = 1;
: my $status = 1;

Are all these variables supposed to be coming from
an HTML form? Is that what you want to use CGI.pm for?


: $dbh-do(INSERT INTO portal (turistobjekt, adresa, brojgrada,
: grad, manjemjesto, otok, regija, ime, prezime, tel, mob, fax,
: email, username,
: password, status) VALUES ('$turistobjekt', '$adresa',
: '$brojgrada', '$grad', '$manjemjesto', '$otok', '$regija',
: '$ime', '$prezime', '$tel', '$mob', '$fax', '$email',
: '$username', '$password', '$status') or die $dbh-errstr); 
: 
: $dbh-disconnect();
: 
: 
: 
: 
: MY QUESTION: How on much simpler way with CGI.pm and
: HTML::template, instead variables my $turistobjekt, my
: $adresa, my $brojgrada etc. RECEIVE any data from html form
: successful?

HTML::Template is used to generate HTML pages. You are
not doing that here. What task are you trying to accomplish,
(besides the DB insert)?

HTH,

Charles K. Clarkson
-- 
Mobile Homes Specialist
254 968-8328




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




RE: create connection from html form into insert MySQL data script

2004-09-07 Thread Maxipoint Rep Office


-Original Message-
From: Charles K. Clarkson [mailto:[EMAIL PROTECTED]
Sent: Wednesday, September 08, 2004 1:06 AM
To: 'Maxipoint Rep Office'; [EMAIL PROTECTED]
Subject: RE: create connection from html form into insert MySQL data script


Maxipoint Rep Office [EMAIL PROTECTED] wrote:

: I am successful insert data in MySQL with code below:

   I am having trouble understanding your message. I assume
English is not your first language.

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

Great start!
RE: yeah.. :-)



: use DBI();
: use CGI;
: use HTML::Template;
:
: # Connect to the database.
: my $dbh =
: DBI-connect(DBI:mysql:database=MYDABASE;host=localhost,
: MYDBUSERNAME, MYPASS,
: {'RaiseError' = 1});
:
: my $turistobjekt = dadas;
: my $adresa = sdasdasdfADRESA;
: my $brojgrada = 1;
: my $grad = 1;
: my $manjemjesto = 1;
: my $otok = 1;
: my $regija = 1;
: my $ime = 1;
: my $prezime = 1;
: my $tel = 1;
: my $mob = 1;
: my $fax = 1;
: my $email = 1;
: my $username = 1;
: my $password = 1;
: my $status = 1;

Are all these variables supposed to be coming from
an HTML form? Is that what you want to use CGI.pm for?
RE: yes, I wish delete it in script and that form send same values using
CGI.pm and HTMP::template



: $dbh-do(INSERT INTO portal (turistobjekt, adresa, brojgrada,
: grad, manjemjesto, otok, regija, ime, prezime, tel, mob, fax,
: email, username,
: password, status) VALUES ('$turistobjekt', '$adresa',
: '$brojgrada', '$grad', '$manjemjesto', '$otok', '$regija',
: '$ime', '$prezime', '$tel', '$mob', '$fax', '$email',
: '$username', '$password', '$status') or die $dbh-errstr);
:
: $dbh-disconnect();
:
: 
:
:
: MY QUESTION: How on much simpler way with CGI.pm and
: HTML::template, instead variables my $turistobjekt, my
: $adresa, my $brojgrada etc. RECEIVE any data from html form
: successful?

HTML::Template is used to generate HTML pages. You are
not doing that here. What task are you trying to accomplish,
(besides the DB insert)?
RE: ok, I can resolve HTML::template alone later, can you help me with
CGI.pm... how send data into inerst script from form? not with variables
like I am create here?

-GP



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




  1   2   >