Re: Module subclassing
[snipped helpful code] : And all is well if I create a new number and print it back, : both bstr() and fmtstr() work just as expected. However any : arithmetics fails with an Unknown round mode '' error. I : looked at Math::Currency which is a rather simple module : and I still can't figure out what am I doing wrong. Can you show us your test cases script, so we can see it fail? Certainly. It's a simple as: use Tools::Currency; my $one = Tools::Currency-new ('1'); print ($one + 1); which yields: perl ./test Unknown round mode '' at ./test line 3 Changing the two occurences of Tools::Currency to Math::Currency makes it work just fine -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Module subclassing (solved)
I am trying to subclass Math::Currency to change the default bstr() and move it to a different function, so my numbers are not formatted by default (I am unable to just strip existing formatting in a certain situation). ... However any arithmetics fails with an Unknown round mode '' error. Crap, it was all written in the POD of Math::BigInt under Subclassing. Adding the following globals to the class package solved the problem: our $accuracy = undef; our $precision = -2; our $round_mode = 'even'; our $div_scale = 40; -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
XML::Simple + Math::Currency / Math::BigInt problem
Hello list. After I converted some parts of my program to use Math::Currency I faced the inconvenience of my XML generators not working anymore. 20 minutes of jumping up and down with the debugger yielded that the following dumbed down example: use Math::Currency; use XML::Simple; my $number = Math::Currency-new ('1'); my $string = XMLout ( { number = $number } ); dies with this: Can't call method as_number on unblessed reference at /usr/share/perl/5.8/Math/BigFloat.pm line 129. If I change Math::Currency to Math::BigInt - the result is slightly different but the thing still dies. Any help would be greatly appreciated 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: BEGIN block question
On Sun, Oct 02, 2005 at 12:34:53PM -0700, John W. Krahn wrote: To sum what up? What who is saying? What previous e-mail? Crap... I apologize, the email was way too long so I stripped it entirely, being sure that the list will se Jendas reply. It was very thorough so I am posting it below: Hello list, I have some trouble understanding why a BEGIN block behaves the way it does. Here are two files to demonstrate: == test = #!/usr/bin/perl use warnings; use strict; use test2 qw($var); our $var2 = 'second'; BEGIN { print I see $var but don't see $var2\n; } = test2.pm === package test2; use warnings; use strict; use Exporter; our @ISA = qw (Exporter); our @EXPORT_OK = qw ($var); our $var = 'first'; 1; What makes the difference? use Module; is roughly equivalent to BEGIN { require Module; Module-import(); } This means that loading the module and executing the free code within happens as soon as the use statement is fully parsed. And therefore before the following BEGIN blocks. (By free code I mean code that's not in a BEGIN{}, END{}, INIT{} or CHECK{} block or a subroutine.) In your example the our $var2 = 'second'; is above the BEGIN{} block, so it it PARSED before the BEGIN block, but is executed only after all code in the main script has been parsed. While a BEGIN{} block is executed as soon as it's fully parsed. Maybe it will be more clear from this example: #main.pl print This runs after all BEGIN blocks and use statements\n; BEGIN { print This is the first thing that runs\n; } print Second thing to run after all BEGIN blocks and use statements\n; use BeginModule; print Third thing to run after all BEGIN blocks and use statements\n; BEGIN { print This runs just after the use statement, but before the free code\n } print This runs the very last\n; __END__ #BeginModule print In BeginModule: This runs after the BEGIN\n; BEGIN { print In BeginModule: This is the first thing in the module that runs\n; } print In BeginModule: This is the last thing that runs in the module\n; 1; __END__ 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/ http://learn.perl.org/first-response
BEGIN block question
Hello list, I have some trouble understanding why a BEGIN block behaves the way it does. Here are two files to demonstrate: == test = #!/usr/bin/perl use warnings; use strict; use test2 qw($var); our $var2 = 'second'; BEGIN { print I see $var but don't see $var2\n; } = test2.pm === package test2; use warnings; use strict; use Exporter; our @ISA = qw (Exporter); our @EXPORT_OK = qw ($var); our $var = 'first'; 1; What makes the difference? 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: BEGIN block question
Just to sum it up, so I make sure I got what you are saying. From the previous e-mail I understand that: * Right after the use xxx statement is parsed the corresponding module which is 'use'd is fully parsed AND executed. This execution includes any top level code not enclosed in subroutines and all subroutines referenced by said code, just like if we were to do 'perl file.pm' * Parsing of the original 'use'r code (even if there are BEGIN blocks defined firther in the 'use'r) continues only after the abovementioned parsing/execution is completed for the 'use'ed module and recursively any other modules it in turn might be 'use'ing. Is this correct? :) Thanks a lot 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: Comparing an array with hash keys
On Fri, Sep 30, 2005 at 10:08:51AM -0400, Jeff 'japhy' Pinyan wrote: On Sep 30, Mark Martin said: I want to compare the elements of an array with the keys in a hash. If matches are found, I want to store the values associated with the matched keys in an array for future processing : my @storage_array = (); foreach $item(@original array) { if (exists $original_hash{$item}) { push(@storage_array, ?? ) } } Your ?? should just be $original_hash{$item}, I expect, although this code could be written far more succinctly as a map(): my @storage_array = map { exists $original_hash{$_} ? $original_hash{$_} : () } @original_array; ... or grep my @storage_array = grep { exists $original_hash{$_} } @original_array; -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Comparing an array with hash keys
... or grep my @storage_array = grep { exists $original_hash{$_} } @original_array; Disregard that, didn't read the question/answer well enough. Bummer... -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
fork() question
I think I am getting the idea of fork() all wrong. Here is an example: my $pid = fork(); if ($pid) { # should apply to parent only? exit; } sleep 1; print Test\n; exit; 'Test' does not print. If I remove the 'sleep 1' - it prints. From what I understood fork creates two identical processes that become completely independent from each other. What am I missing? Peter -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Math::Currency compilation failure
Hello list, I am trying to install Math::Currency from cpan and I can not make anything out of the error message I get. Any advice would be appreciated. Peter a bucnh of other info, contains no errors CPAN.pm: Going to build J/JP/JPEACOCK/Math-Currency-0.40.tar.gz Checking if your kit is complete... Looks good Writing Makefile for MathCurrency cp lib/Math/Currency/EUR.pm blib/lib/Math/Currency/EUR.pm cp lib/Math/Currency.pm blib/lib/Math/Currency.pm cp lib/Math/Currency/GBP.pm blib/lib/Math/Currency/GBP.pm cp lib/Math/Currency/JPY.pm blib/lib/Math/Currency/JPY.pm Manifying blib/man3/Math::Currency.3pm /usr/bin/perl -Iblib/arch -Iblib/lib Build.PL Build Creating custom builder _build/lib/My/Builder.pm in _build/lib/My Too early to specify a build action 'Build'. Do 'Build Build' instead. make: *** [Build] Error 9 /usr/bin/make -- NOT OK Running make test Can't test without successful make Running make install make had returned bad status, install seems impossible -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Math::Currency compilation failure
Hello list, I am trying to install Math::Currency from cpan and I can not make anything out of the error message I get. Any advice would be appreciated. Peter a bucnh of other info, contains no errors CPAN.pm: Going to build J/JP/JPEACOCK/Math-Currency-0.40.tar.gz Checking if your kit is complete... Looks good Writing Makefile for MathCurrency cp lib/Math/Currency/EUR.pm blib/lib/Math/Currency/EUR.pm cp lib/Math/Currency.pm blib/lib/Math/Currency.pm cp lib/Math/Currency/GBP.pm blib/lib/Math/Currency/GBP.pm cp lib/Math/Currency/JPY.pm blib/lib/Math/Currency/JPY.pm Manifying blib/man3/Math::Currency.3pm /usr/bin/perl -Iblib/arch -Iblib/lib Build.PL Build Creating custom builder _build/lib/My/Builder.pm in _build/lib/My Too early to specify a build action 'Build'. Do 'Build Build' instead. make: *** [Build] Error 9 /usr/bin/make -- NOT OK Running make test Can't test without successful make Running make install make had returned bad status, install seems impossible Looks like cpan does not support this particular deployment scheme. Installed it succesfully by going into ~/.cpan/build/Math-Currency-0.40 and manually running perl Build.PL ./Build test ./Build install -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Can't figure out Error.pm
On Sun, Sep 18, 2005 at 07:14:16AM -0700, Peter Scott wrote: On Sun, 18 Sep 2005 01:43:42 -0500, Peter Rabbitson wrote: sub get_values { #fail right away throw DBException (Sorry, bank is empty); } Each exception needs to be a class that inherits from Error, so: BEGIN { @DBException::ISA = 'Error' } The way the documentation was written I thought that throw is an exported subroutine, whereas in reality the example meant DBException-throw(whatever). Indirect invocation sucks :) By the way, since I throw the exception above as plain text (not as hashref with -text = ), I need to inherit from Error::Simple. This raises another question though - I thought in order to have a class I *must* declare a package. However you get away by simply initiating a variable. Does autovivification work for packages just like it does for hash keys? 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
Assignment modifiers
I stumbled upon a script with the following assignment: ... = v(numeric value); I tried to see how it works and the following: my $a = v65; print $a; produces ascii 65 (capital A) Where can I read more about these assignment modifiers? Peter -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Question about data storage
Hello perlers, This is somewhat of a database related question, but it is as much related to programming practices, so excuse me if this is not the apporpriate list. I am collecting and processing online orders from several different sources. Each source is queried periodically, information about new orders is retrieved, parsed, and presented to a central table in a unified form (orders end up looking alike, no matter where they came from). Then they are grouped, printed and so on and so forth. The problem is that some of the sources allow orders to be submitted with bogus information (as 6 digit zip codes), so these orders must aggregate in an intermediate container, and wait for an employee to make necessary changes through a web interface. What I can not decide is how to implement this intermediate container. So far I have thought of the following options, but each has a fairly serious shortocmming: * I store dirty orders alongside approved orders in my SQL tables. The problem is that unlike approved orders, where each field has passed a content/length check, the dirty order might have a string in a place where only nemerics are expected - thus preventing me to store this piece of information. If make separate tables for accepted and dirty orders, I still face the problem that almost all fields must be of arbotrary length (TEXT/BLOB) since I can not be sure of the individual field sizes. * I store dirty orders as XML in a SQL table with 2 columns - one for the order id and another for the arbitrary XML structure. Problem once again is that my XML can be thousands of characters long. * I store dirty orders as XML in a native format like BDB. Problem is that I lose the fine grained user access control that a RDBMS gives me, must give the web interface access to the DB file, and invent algorithms to deal with multiple users trying to access dirty orders and cleaning them. I currently use MySQL for the rest of my application needs. An average order expressed in XML is about 2000 characters/bytes long. There shouldn't be more than 100 dirty orders concentrated at a given time, so theoretically speed will not be an issue, as before processing I should be able (?) to load the entire dirty database in memory and perform operations on parts of the hash tree. What would you suggest? By the way if there is comprehensive reading on the subject that I failed to locate - I would love to see it. Thank you 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: Question about data storage
On Thu, Sep 15, 2005 at 04:57:28PM -0500, Walter Hunnel wrote: Not perl, but as a DBA: Thanks for answering! Unless you are getting the data as XML or have to change the data to XML for some other reason, I would not move to XML just for the cleanup you are asking about. I was considering XML because of the structural complexity of the data. At some places internally you get a hash-of-hashes-of-hashes-of-hashes situation, and I wanted to maintain some ability to search those as well (although painfully slow) - so it had to be clear text. As XML is most portable - I decided to choose it using XML::Simple to pack and unpack the structure, in leu of Data::Dumper or YAML. You seem to be questioning my use of XML - is there a reason not to do it? I will stick with Data::Dumper if it poses a problem I am not aware about. Understanding that you specify that you are accepting data from other sources and may not have control of validation of the data before receiving it, you have no choice but to accept ANYTHING, store it, validate it, and deal with garbage as necessary. This is precisely correct - no control over any of the sources, and unfortunately a couple of broken sources. And this is the whole reason I am doing it - I need to hold the data efficiently, yet intact until a human decides how to change it or whether to keep it at all. I have to assume that the data is delimited in some way, so perhaps you can parse the delimited data and decide based on that what to do with the bad data. If that is the case, you can validate each field and any invalid field data can be stored in a separate table with an associated key and the key used in place of the data - so the valid data is stored where it should be and only bad data is stored in the other table, but you can rejoin them when giving the bad data to a human for interpretation. In that case, you need only two columns, a key and a large field to hold the bad data, every thing in the main table would meet the data restriction requirements. Of course, you would need to check for bad data table keys in ANY column before printing out any row, or use the flag idea from above... Yes, this is exactly how it works. Each source returns data in its own format which I parse with a designated helper, and mark what needs to be looked at right there. The problem once again was how to store it intact until someone looks at it. The above is not a bad idea, but it will get messy when my dirty table index grows bigger than one of the limits for the fields in the accepted table. Then I will not be able to insert a pointer to the dirty table to the field, because the pointert value itself becomes illegal for that field. On the other hand I can add an additional dirty column which will signify that there is SOMETHING in the dirty table waiting to be joined with the rest of the data. In the dirty table I keep a keyed structure in the second column, once again something like XML or alike... Then of course comes the question wether it's worth the hassle, and why not just store the entire dirty order as it is in a dirty table, which is what I am leaning to. Currently doing some tests on how big the table gets worst case scenario (somebody doesn't do his job and dirty orders keep piling up). Thanks for the hints though :) Peter -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
UNIVERSAL class like functionality for non-OO?
Hello list, Is there a clean and elegant way to make a subroutine available to all namespaces/packages? Something like the UNIVERSAL class for objects, but for non-OO environment. I need to embed a logging facility into a multimodule project, so I want to have a certain function (say log_msg() ) to be available anywhre in the program, without importing it in each and every module. 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: Forcing array context
On Sat, Aug 20, 2005 at 08:44:34PM +0530, Binish A R wrote: How can I force array context ... like # echo hello: world | perl -lne '$aref = split(/:/, $_); print $aref' but thatz giving the length of the array ... I want $aref to be a reference ... How is that possible ?? Very simple: my @list1 = (1,2,3,4); my @list2 = (5,6,7,8); my @combined = (@list1, @list2); my $ref_combined = [ @list1, @list2 ]; For mor info look in the Perl Cookbook section 11.0 (References and Records - Introduction) -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Forcing array context
perldoc -q What is the difference between a list and an array As a side note to the POD above - although lists can not change sizes they are addressable just like arrays. In other words the following two statements are equivalent: my @slice = @{ [ (split /\|/, 'a|b|c|d|e') ] }[1,3]; my @slice = (split /\|/, 'a|b|c|d|e')[1,3]; 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: array of hashes of arrays...
On Mon, Aug 15, 2005 at 04:08:22PM -0500, The Ghost wrote: How can I do this correctly? foreach my $col (@columns) { my %{$col} = ( # -- I have a problem here, I want the hash to be named whatever $col is string = $col, number = [EMAIL PROTECTED] ); push (@graph, \%{$col}); } -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response Even if you did generate hash names on the fly (which is not a very good idea) you still have no benefit whatsoever. After creating %{$col} you use the reference to it, which effectively destroys the information about the variable name (a reference is a pointer to an in memory structure, be it hash, array or something else, not to a variable name). Then on the next foreach %{$col} falls out of scope and is effectively reinstated as a brand new hash. In other words the above is equivalent to: foreach my $col (@columns) { push (@graph, { string = $col, -- no need for quotes number = [EMAIL PROTECTED] -- where did this come from? } ); } -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: searching an array reference
I'd like to search that array and push to it if a value isn't there. At the moment I'm dereferencing the array, searching/pushing it and the passing it back to the class as an array ref again. So this mean copying the array. Code: my @used_images = @{$_[0]-{_used_images}}; foreach (@imgids) {push(@used_images, $_) unless (grep { /^$_$/ } @used_images);} $_[0]-{_used_images} = [EMAIL PROTECTED]; The way you wrote it is very confusing, and I actually doubt you get the result you want (too lazy to run it). Avoid relying on $_ when you have to use it with different values on the same line (e.g. you push $_ to @used_images AFTER it has been reassigned by the grep on the last element of @used_images). To answer your actual question - no you don't have to copy the array. You can work on an aray behind a reference just like you did the assignment to @used_images in the first line. Also using eq instead of a regex (which in your case is equivalent to an eq anyway) is times faster. foreach my $new_id (@imgids) { unless (grep { $_ eq $new_id} ( @{$_[0]-{_used_images}} ) ) { push @{$_[0]-{_used_images}}, $new_id; } } And last but not least - if you need unique values why don't you just use a hash for this data branch? If @imgids contains 500 elements and $_[0]-{_used_images} contains 5000 you will run through the inner loop exactly 250 times which will cost you even on a very fast machine. Peter -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
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
Re: DBI insert vs update question
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
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
Yet another question on perl modules
Hello everyone, Most modules I run across have a BEGIN block containing some variable declarations, module loaders etc. Although I understand what BEGIN is (code being evaluated immediately after it is parsed), I miss the point of the excercise. For example: package csv_generator; use Text::CSV_XS; our $ERROR; sub new { my $class = shift; return (bless {}, $class); } sub add_line { my $self = shift; push @{$self-{pending}}, [EMAIL PROTECTED]; return 1; } sub wrap_csv { my $self = shift; my $csv = Text::CSV_XS-new; my @result; foreach my $line @{$self-{pending}} { $csv-combine (@{$line}); push @result, $csv-string(); } return (join (\n, @result)); } Where would BEGIN come to play? P.S. I know the above code is messy, without any error checking, and I might even have a typo somewhere. It is just for illustration purposes. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Yet another question on perl modules
On Thu, Jul 07, 2005 at 02:22:34AM -0400, Casey West wrote: This is a confusing question, but I think the answer is that a BEGIN block would come into play before any of these things are executed. -- Casey West Sorry :) Question is: why would I want to use a BEGIN block in the above script skeleton. What advantages would BEGIN give me that I can not have otherwise, and why most modules bear one (some more than one). -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
usage of do {}
Hello everyone, Here and there on the web I encounter claims that the do {} operator is depreciated. However I find it convenient to do things like: eval { some stuff } or do { some multiline error handling }; is this a bad practice? 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: usage of do {}
On Thu, Jun 30, 2005 at 09:05:00AM -0600, Wiggins d'Anconia wrote: Peter Rabbitson wrote: Hello everyone, Here and there on the web I encounter claims that the do {} operator is depreciated. However I find it convenient to do things like: eval { some stuff } or do { some multiline error handling }; is this a bad practice? Thanks Peter Didn't see anything about 'do' being deprecated in the perldoc -f do or perldoc perlsyn docs. Though do SUBROUTINE was stated as deprecated. The problem (IMHO) with the above is that you can't return a positive value from the eval and you haven't error checked whether there was an exception thrown, which is one of the more common reasons to use an eval in the first place. So I guess my question is, why are you using the eval to begin with? my $return = eval { some stuff }; if ($@) { rethrow or handle Eval failed with: $@; } unless ($return) { some multiline error handling; } The problem is that eval returning a false/undefined value shouldn't necessarily have to indicate failure. And if the 'eval' isn't catching an exception then there is really no reason to use it in the first place. I am sorry, I wasn't clear enough. I am aware of eval returning the last statements return value, thus the possibility of having an undef result. I am using it exclusively for control of do or die tasks, as DBI operations for example, where even if it returns 0 it still evalutes true. The reason I do () an entire block is because I specify additional error messages. Like this: my $dsn = join (':','DBI', $cfg-{engine}, join (';', database=$cfg-{database_name}, host=$cfg-{host}, port=$cfg-{port}, ), ); my $dbh; eval { $dbh = DBI-connect ($dsn, $auth-{user}, $auth-{pass}, { AutoCommit = 0, RaiseError = 1, PrintError = 0, } ) } or do { $ERROR = Unable to connect to '$dsn':\n . ($DBI::errstr || 'Unknown error'); return undef; }; return $dbh; Thanks for the feedback 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: usage of do {}
Just as a side note... this is really a stylistic or idiomatic argument. snip Precisely right. That once again is a bad example I guess :) It is just dictated by the way all the rest of the error handling is done. For example: sub check_table { my ($dbh, $table) = @_; $table = lc $table; my $tab_ref; eval { my $tb_h = $dbh-table_info (); $tab_ref = $tb_h-fetchall_arrayref (); } or do { $ERROR = Execution of DBI-table_info() failed:\n . $dbh-errstr; return undef; }; unless (grep { ($_-[2] eq $table) and ($_-[3] eq 'TABLE') } @{$tab_ref} ) { $ERROR = Table '$table' does not exist; return undef; } my $col_ref; eval { my $cl_h = $dbh-column_info (undef, undef, $table, '%'); $col_ref = ($cl_h-fetchall_hashref ('COLUMN_NAME') ); } or do { $ERROR = Execution of DBI-column_info() for '$table' failed:\n . $dbh-errstr; return undef; }; my @expected_columns = describe_table ($table); if ((keys %{$col_ref} != scalar @expected_columns) or (grep { ! defined $col_ref-{$_} } @expected_columns) ) { $ERROR = Layout of '$table' is invalid; return undef; } return 1; } So the connect() subroutine which you saw in the previous mail simply follows this model, although it is a different animal on the inside. 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: What does this error message mean?
print g++ $ARGV[i] \n; Argument i isn't numeric in array element at ./cedit01 line 61. It is exactly what it says - the string 'i' is not numeric and you are using it as an @ARGV index. Perhaps you meant $ARGV[$i]. Furthermore the whole c-loop construct is not very appropriate as perl has its own built-in array iterator: foreach my $argument (@ARGV) { print g++ $argument \n; } -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
DBI + forking (was: DBI + XML::Twig conflict)
Just to sum up the discussion as it was extremely helpful and educational: Hm... I get it and I don't get it... Who keeps the sub _dummy - the parent or the child? I need to use DBI in it so I guess InactiveDestroy must be set to true there. How do I find out who is who not at the time but after the fork? Is this portable to win32? (the final version must run on win32 as well). Actually from the little I know about forks I thought that both parent and child get copies of the very same stuff. So both get a hot DBI and DBD::Mysql tied to the same socket... if this is at all possible. On the other hand I am not using DBI anymore while in the reader (child?), just the parser, so it shouldn't matter... Wow I am even more confused now :) Ah, fun with IPC :-). The sub _dummy is the parent, because that is what you are controlling, technically you aren't even supposed to be aware that there is a fork (and weren't, really, until I told you :-)). Yes you are correct, everything is shared across the fork, the $dbh being one of those things. Normally if you were controlling the fork/exec model then you could decide to set InactiveDestroy in whichever place it was needed, it would actually be the child as that is what is exiting early (it does the retrieval). But in this case since the fork/exec is encapsulated in a module you didn't write, you will likely want to set it at connection time so that it is set on both of the handles. The key in this case is that you have to do your explicit commit/disconnect (which you were already). Theoretically another option would be to set it during construction, then unset it in the parent after the fork, assuming this works as I am thinking (caveat), then that might be better as it should make sure to do the normal DBI cleanup. Of course back to my caveat, since you don't really have control of when the fork is going to exit this might be trickier. Though *I think* (no guarantee) that the parser is reading from the pipe created for the fork, so as long as the parser isn't finished the pipe and child should be active. Sorry if I am confusing you again, the route I would take would be to set it during construction because that is the simplest, then test, test, and test some more. Try it different ways and see which works the best in the tests. See if you can get it to break again. I didn't like the second variant, mainly because this really throws the whole cleanup mechanism of DBI in the bucket. Suppose I made a typo that will cause the whole thing to die at runtime. Depending on the database engine I could get an undesired commit of the last transaction if the socket just closes. The natural thing to do for me was to preceed the call of the forking function (namely parseurl) with ++$dbh-{InactiveDestroy} and then add undef $dbh-{InactiveDestroy} as the first line of _dummy(). Worked like a charm since then. Whether or not this works correctly on Windows I have no idea, and wouldn't even venture to guess. You may want to read up on IPC on windows and fork/exec for that platform. Looks like everything works fine, however I did only several test runs, leaving the main drill for when I will be testing the entire thing under Win32. On an unrelated note - is there a generic way to trap this kind of things? Or way to do partial forks (e.g. disable socket sharing)? Probably those situations do not happen very often, but if I use a module that is not um... ForkSafe like DBI (in other words it does not offer a way to skip the destructor), and if I use some fat module from CPAN that relies on another group of modules just as fat and so on and so forth, and I end up with a fork() encapsulated several levels under the main::use pragmas - starts sounding like a nightmare. etc. Watch out for the slippery slope with this argument, I mean, you could just write it all without modules, you could write it all in C, you could write it in assembly! Boy what fun that would be. I just made up my mind about my after-retirement plans! :) 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
Change the format of $@
Hello, Consider: perl -e 'eval { die Error message:\nVerbose error message: }; print $@;' Error message: Verbose error message: at -e line 1. ^ Is there an easy way to get rid of the marked part? 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: sorting array full of hash references
On Tue, Jun 07, 2005 at 10:40:43PM -0400, Jeremy Kister wrote: I'm stumped on how to sort an array based on a hash refrences's key in each element of my array. this is dumbed down code of what I have: my @array; while(my $row = $sth-fetchrow_arrayref){ my %hash = (id = $row-[0], name = $row-[1]); push(@array, \%hash); } after the while loop, I'm trying to build a new version of @array, sorted by the 'name' key. Sort as its first argument can take a code block with the two special variables $a and $b passed to this block for each iteration of the sort algorithm. The return values must must be one of -1 0 or 1, which have the same meaning as in the cmp and = comapriosn operators. In other words in you case you want to do: @array = sort { $a-{name} cmp $b-{name} } @array; I hope the dereferencing above is pretty self explanatory. Try perldoc -f sort for more info - there are some pretty nifty examples in there. Peter -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
DBI + XML::Twig conflict (?)
I have a strange problem where a database handle is being destroyed for no apparent reason. My initial idea was to parse some xml, and translate it into a database. Deleting line after line of code I came up with this short meaningles program which exhibits the same behavior as its real-life sibling (tested against two different mysql instalations on different machines): use warnings; use strict; use DBI; use XML::Twig; ++$|; #so I can see the progress in _dummy () my $dbh = DBI-connect ( dbi:mysql:$random_db:localhost, $user, $pass, {AutoCommit = 0, RaiseError = 1, PrintError = 0, } ); unless ($dbh) { print Unable to connect:\n$DBI::errstr\n; exit 1; }; eval { $dbh-do (DROP TABLE IF EXISTS some_nonexistant_table) }; die ($@) if $@; my $objinfo_parser = XML::Twig-new ( twig_handlers = { 'Products/Product' = \_dummy } ); $objinfo_parser-parseurl ('http://www.3btech.net/3btech/objinfo.xml'); $dbh-commit; $dbh-disconnect; exit 0; sub _dummy { my ($twig, $child) = @_; print '.'; $twig-purge(); return 'dummy'; } Note that I am not even doing any real operations on the MySQL side, thus I don't care what database I connect to. I put the DROP TABLE there just to make sure that commands are reaching the server, and yes I can see that in the logs. If I run the real program I end up stuffing about 480 out of roughly 510 products into a designated table and then the handle goes out to lunch with the same error message. I use the very same XML::Twig setup in another script that packs results into a hash and returns it, and everything works flawlessly. Any help is priceless, as after nearly two days playing with this I am totally lost... 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 + XML::Twig conflict (?)
If I run the real program I end up stuffing about 480 out of roughly 510 products into a designated table and then the handle goes out to lunch with the same error message. What's the error message? Ups... I guess I missed that: ~$ ./test /dev/null Issuing rollback() for database handle being DESTROY'd without explicit disconnect(). DBD::mysql::db commit failed: MySQL server has gone away at ./test line 27. -- 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 + XML::Twig conflict (?)
Thank you. No guarantees, but try setting 'InactiveDestroy' when you create the DB handle. XML::Twig uses a fork/exec call in 'parseurl' to retrieve the URL in one process and to parse the XML in the other. When the retrieval is complete one of the processes closes with an 'exit'. I think because the $dbh is shared (because it just is) you are getting the above result. The switch I mentioned appears to be designed for this specific case. For more info see InactiveDestroy here: http://search.cpan.org/~timb/DBI-1.48/DBI.pm#ATTRIBUTES_COMMON_TO_ALL_HANDLES This attribute is specifically designed for use in Unix applications that fork child processes. Either the parent or the child process, but not both, should set InactiveDestroy on all their shared handles. HTH, Hm... I get it and I don't get it... Who keeps the sub _dummy - the parent or the child? I need to use DBI in it so I guess InactiveDestroy must be set to true there. How do I find out who is who not at the time but after the fork? Is this portable to win32? (the final version must run on win32 as well). Actually from the little I know about forks I thought that both parent and child get copies of the very same stuff. So both get a hot DBI and DBD::Mysql tied to the same socket... if this is at all possible. On the other hand I am not using DBI anymore while in the reader (child?), just the parser, so it shouldn't matter... Wow I am even more confused now :) All above considered - I guess I would be safer downloading the file somewhere and doing safe_parsefile to avoid any forking altogether. Thanks for the hint -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
XML::Twig exception handling
Hello, I am interfacing an XML file with a database, much like the last example at http://www.xmltwig.com/xmltwig/tutorial/yapc_twig_s5.html What I am actually doing is checking if the table already got such a record, if so - updating it, otherwise inserting it, but this is not relevant. Either way I can't figure out how to raise an exception in the insert_row subroutine so that the parsefile() will die as well. Since I am working with records totalling several gigabytes, I am checking every SQL operation by evaling them with RaiseError turned on. This doesn't help me much, however, since the best I can do after a failure is return from the subroutine and XML::Twig will continue with its business. I could issue a finish() and the parser should (?) stop processing the XML, but it will still return with a success (I am performing safe_parsefile), and it actually doesn't seem to stop at all, chewing through the rest of the file. If this is true (finish() works as I think it works) then I guess I could use a global flag that will be raised if one of the inserts fails. Then after the parsefile() I will check it and rollback all changes to the db, but this seems really retarded. Are there some better ways to do this that I am overlooking? 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: XML::Twig exception handling
Either way I can't figure out how to raise an exception in the insert_row subroutine so that the parsefile() will die as well. Since I am working with records totalling several gigabytes, I am checking every SQL operation by evaling them with RaiseError turned on. This doesn't help me much, however, since the best I can do after a failure is return from the subroutine and XML::Twig will continue with its business. I could issue a finish() and the parser should (?) stop processing the XML, but it will still return with a success (I am performing safe_parsefile), and it actually doesn't seem to stop at all, chewing through the rest of the file. If this is true (finish() works as I think it works) then I guess I could use a global flag that will be raised if one of the inserts fails. Then after the parsefile() I will check it and rollback all changes to the db, but this seems really retarded. Are there some better ways to do this that I am overlooking? Some days I am dumber than other days. If I die() inside the handler subroutine, parsefile dies as well, and is caught be the global eval created by safe_parsefile. Excuse the noise :) 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: absolute path of current process
On Thu, May 26, 2005 at 02:26:29PM +0300, Offer Kaye wrote: On 5/26/05, Peter Rabbitson [EMAIL PROTECTED] wrote: Is this: my $path = [File::Spec-splitpath (File::Spec-rel2abs ($0))]-[1]; the only OS independent (unix/win32) way to determine the absolute path of the directory which contains the current process, or there is a less cryptic way that I am overlooking? What do you mean by current process? If you mean the path to the currently running executable ($0), You can use a combination of the abs_path function from Cwd together with dirname from File::Basename : use Cwd qw(abs_path); use File::Basename qw(dirname); my $path = dirname(abs_path($0)); However please note that the current process may be running in an entirely different directory then the one that hold the executable. To find the current directory, use: use Cwd qw(cwd); my $path = cwd(); I meant the absolute dir containing the executable. Thing is I want to throw a config file in the same dir that will be found regardless of how the thing got started (from the program dir with ./, from a different dir with absolute path, with relative path, from cron, etc.). In other words exactly what you proposed. Btw looking at the source both you and mine methods end up using the same core modules. I guess for this there isn't really TIMTOWTDI. OTOH mine does not pollute namespace and yours is more readable. Counts as more than one way I guess :) Thanks -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Database independent code
Hello, I need to implement some database access in my code, and my knowledge of databases is pretty basic (mostly MySQL ans flat un-indexed tables). Can somebody point me to advanced tutorials on database independent code? For example I can't find a way to tell what methods from DBI and family can I use without concern that the code will break if tomorrow the database engine will have to change. Also I am trying to figure out what is the most commonly accepted way of storing complex data structures like arrays-of-hashes-of-hashes-of... in databases. The first thing that comes to my mind is describing the entire branch in each table row, in other words working the enumeration back to the root of the structure, ordering the rows accdording to key and array index occurences. This however does not seem very efficient as far as table size management goes. Some preliminary searching turned up a possibility of storing XML as table data which also seems too inefficient to me. So anyway, if someone could share a good reading on the subject that he came upon would be most helpful. 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: Hash of Arrays, p. 276
Please look at the definition and initialization of the hash. It is a hash of array references, isn't it? Why does $HoA{flintstone}[0] work, why is not it: $HoA{flintstone}-[0] perldoc perlref Section: Using References Paragraph 3 $array[$x]-{foo}-[0] = January; . One more thing here. The arrow is optional between brackets subscripts, so you can shrink the above down to $array[$x]{foo}[0] = January; . -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
absolute path of current process
Is this: my $path = [File::Spec-splitpath (File::Spec-rel2abs ($0))]-[1]; the only OS independent (unix/win32) way to determine the absolute path of the directory which contains the current process, or there is a less cryptic way that I am overlooking? P.S. I know the above will not work if somebody tinkers with $0, but this is not relevant to my situation. 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: absolute path of current process
On Thu, May 26, 2005 at 05:38:50AM -0500, Peter Rabbitson wrote: Is this: my $path = [File::Spec-splitpath (File::Spec-rel2abs ($0))]-[1]; the only OS independent (unix/win32) way to determine the absolute path of the directory which contains the current process, or there is a less cryptic way that I am overlooking? My bad, to work on win32 it becomes even more cryptic: my $path = join ('',@{[File::Spec-splitpath (File::Spec-rel2abs ($0))]}[0,1]); -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: efficiency of hash of hashes/lists
On Mon, May 23, 2005 at 01:40:08PM -0400, Zhenhai Duan wrote: I tried hash (where the members of a group are joined with :), and hash of hash. It happended that hash of hash is slower than single hash. Hash: $groups{$g1} = $member1:$member2; Hash of hash $groups{$g1}{$member1} = 1; Method 1 is faster, even I need to do a split to get the members. Can you post some code? Without it the above statement is not very credible to say the least. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: foreach loop current index
The reason this has not been built into the language is that there would be an overhead associated with each loop to maintain this variable. The Perl5 team felt that this was not acceptable given that most loops do not need this information and, and you have noted, it's trivial to do the work yourself if necessary, if not always terribly elegant. Paul Johnson - [EMAIL PROTECTED] http://www.pjcj.net This is exactly what I was looking for. Thank you :) Peter -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
foreach loop current index
Hello, When perl executes a foreach loop, it creates some kind of array of all the iterators and then goes over them one by one. Is the current index pointer accessible from inside the loop? I was unable to find anything related in perlvar. Thanks for the input Peter P.S. I know it is trivial to add an incrementing counter at the end of the loop, but it seems redundant to me, since perl got to do something similar anyway just to keep track of its own state. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: foreach loop current index
foreach $item ( @list ) { sub( $item ); } Are you sure this is not a typo? I've never seen a sub statement taking a list argument... Besides this is what I get if I run it anyway: [EMAIL PROTECTED]:~$ cat 123 @list = qw(a bc c); foreach $item ( @list ) { sub( $item ); } [EMAIL PROTECTED]:~$ perl 123 Illegal declaration of anonymous subroutine at 123 line 4. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: foreach loop current index
When perl executes a foreach loop, it creates some kind of array of all the iterators and then goes over them one by one. Is the current index pointer accessible from inside the loop? I was unable to find anything related in perlvar. I think I should clarify myself a little. Here is an example: my @lsit = qw(a b c d); my %indexes; my $current_index = 0; foreach my $element (@list) { $indexes{$element} = $current_index; ++ $current_index; } What I was saying above is that (as far as I understand) perl keeps its own $current_index-like variable to track how far it is into the foreach. Is there a way to use it inside the loop instead of $current_index, thus saving (although negligible) incrementation operation. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: foreach loop current index
On Sat, May 21, 2005 at 12:11:42AM -0400, Chris Devers wrote: On Fri, 20 May 2005, Peter Rabbitson wrote: my @lsit = qw(a b c d); my %indexes; my $current_index = 0; foreach my $element (@list) { $indexes{$element} = $current_index; ++ $current_index; } Ah. Maybe this? for (0 .. $#list) { $indexes{$list[$_]} = $_; } Closer? Kinda... although it doesn't answer my initial question about the internal variable :) Thanks though. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Errors on processing 2GB XML file by using XML:Simple
I have to say that I'm very lucky because the document keeps a very well defined order of topic/ and ExternalPage/... Not really, think how much programming effort would it take to generate a file where Topic/ and corresponding ExternalPage/ would be intermixed :) The last question about my approach is, I found a good place to close an opened file handler, it's just the first line in sub _topic_handler, however, how can I write some if statement to say, if FH is opened, then close it? Assuming that you keep only one file open at a time and your filehandle is the same for all files (e.g. FH) you can simply add to the very start of _topic_handler: close (FH) if (fileno FH); read perldoc perlfunc to see what fileno does. 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: Errors on processing 2GB XML file by using XML:Simple
I know the answer of second question after reading a quick reference of twig... You know the answer to your first question as well - you've been looking at it the whole day :) I have examined the XML file and all Topic/with link/ children are followed by their own ExternalPage/s. If there is a Topic/ without link/ inside, it is followed by a new Topic/. You wrote this paragraph yourself. Doesn't this sound like natural interleaving? codes, I found that the execute order of these two subroutines is: Topic/ - if no link/ child, go to the next Topic/ - if there is link/ child, go to its following ExternalPage/ - until there is no more Topic/ nodes. I don't know that which part of codes control this order, is it because of the order of two handlers you set in twig_handlers which indicates the twig process should be interleaving? Once again - you first wrote the answer, then wrote the question to it. Read it again (and again if it's necessary :) 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: Errors on processing 2GB XML file by using XML:Simple
Your codes look great and it works perfectly with only some minor problems which might due to the XML file itself (I think). However, compared your codes with mine, there are something I'd like to ask you if you don't mind. Not that much :) 1) what's the main difference on memory load bewteen setting handlers and without setting handlers before calling $parser-parsefile($xml)? Does it mean that yours actually access the XML file partially, the first handler only treats for Topic/ and the last handler is only for considers ExternalPage/. If so, does setting handlers actually change the way of loading a file? Take a look at the XML snippet you sent me as sample data. You have a regular text file with variable data fields (in other words different keywords/flags/operators/tags etc have unpredictable length/size in bytes). So the only way to read such a file is going byte by byte and analyze everything as we go. What you were doing in your code is doing this byte by byte reading up until you don't encounter an EOF, which was taking the corresponding amount of memory. Now let's break your example apart (I am deliberately ommiting lots of data and adding some): RDF Topic 1st topic related data /Topic ExternalPage 1st external page related to 1st topic /ExternalPage ExternalPage 2nd external page still related to 1st topic /ExternalPage Topic 2nd topic related data /Topic ExternalPage 1st external page related to 2nd topic /ExternalPage Topic 3rd topic /Topic SomeOtherTag Some Other Data /SomeOtherTag Topic 4th topic /Topic ExternalPage 1st external page related to 4th topic /ExternalPage ExternalPage 2nd external page still related to 4th topic /ExternalPage /RDF Then the following parser declartion: my $parser = XML::Twig-new ( twig_handlers = { 'Topic' = \_topic_handler, 'ExternalPage' = \_links_handler, }, ); $parser-parse($xml); simply means: Start walking through the XML data (variable, file, url) and keep going until you see a completed tag (opening tag followed by arbitrary amount of data and then closing tag). If the tag we just found matches the twig handler Topic.../Topic - call subroutine _topic_handler and pass as arguments the twig, in other words this particular tag object, and all children, in other words all subtags between Topic and /Topic. At the end of each _topic_handler subroutine I took all I needed from the passed twig, so I can safely throw it away thus reclaiming memory - I execute a -purge. Same goes for _links_handler 2) My understanding about your codes is, first you looked at Topic/ nodes and found if they have link/ child/children, if they have, you saved them into a hash table for later ExternalPage/ comparisions. But my question is, how are you going to search all Topic/ and all ExternalPage/one by one by just call the subroutine once without using any kinds of loop? and how can you link these 2 handlers together? It is the $parser-parse($xml) line that creates the loop - it will keep going until there is data in the XML, just like while () will keep going until there is input from STDIN. Everytime we see a tag set defined in twig_handlers we will call the corresponding subroutine and do whatever we got to do. Keep in mind that if it encounters something else that is not described in the handlers (just like SomeOtherTag between the 3rd and 4th Topic) it will simply be ignored without occupying any memory. This is why you can use XMLTwig to process huge files out of which you need several scattered tags. 3) My original intention is for each Topic/ with valid link/ child/children, to open a file in a directory named exactly the same as what is found in a Topic-att('about') then write all links information found in ExternalPage/ then close the file. However, after reading at your code times and times, I don't know where should I close the file handler because sub _links_handler is used for finding out links one by one and I don't know when a ExternalPage/ is finished from parsing. This is exactly why I said - if Topic is not ALWAYS followed by its OWN ExternalPage links - you are screwed. If this is the case you will never know if you should expect yet another ExternalPage tag somewhere after 1GB of data that will refer to a Topic in the very beginning of the file. Thus I assume in my code that when we see another Topic we are done with the previous one, this is wht I was completely reassigning %want_links, because I do not expect any
Determine structure size
Is there a way to determine how much a certain data structure costs in terms of memory? In other words is there some built in command or module that takes a reference to a nested data structure and gives a ball park idea of how much memory this structure takes. 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: Removing multiple spaces
$str =~ s/ / /i; $str =~ s/ / /i; $str =~ s// /i; $str =~ s/ / /i; $str =~ s/ / /i; $str =~ s/ / /i; $str =~ s// /i; $str =~ s/ / /i; $str =~ s/ / /i; is the same as: $str =~ s/\s{2,10}/ /; Read perldoc perlre, especially the part about quantifiers. Peter -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
HTTP Upload of a filehandle
Could somebody point me to a resource of how to upload a file using LWP via a data string or a filehandle such a string (I don't want to create a temp file on disk just to delete it after the upload). Thank you 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: Removing multiple spaces
$str =~ s/ / /i; is the same as: $str =~ s/\s{2,10}/ /; Not quite. The \s character class includes more than just the ' ' character. My bad :D -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Errors on processing 2GB XML file by using XML:Simple
I have tried to use XML:Twig to parse a 2GB XML file instead of using XML:Simple, but I still got an error The memory couldn't be written. My Perl is the latest and my RAM is 1GB. Are you issuing a $twig-purge at the end of each handler? Without it memory is not implicitly released (no garbage collection so to speak). Or maybe you are trying to construct a twig with a malformed root and you are ending up reading the entire file (in other words the twig does not know when to stop until it runs out of data, or in your case runs out of memory). 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: Errors on processing 2GB XML file by using XML:Simple
Basically, the XML file has two key parallelled nodes: Topic/ and ExternalPage/. If there is a link/ child existing in Topic/, ExternalPage/ node will be existing for showing more detailed information about the content of this link/ such as d:Title/ and d:Description/. However, not every Topic/ node has one or more link/ child, so I need to write a loop to find out if link/ is a child of Topic/ nodes. If there are some link/ nodes existing, I will check each of ExternalPages to output more information. Can you provide some relevant code? Looking at the sample xml two handlers immediately come to mind, one for RDF/Topic another for RDF/ExternalPage, both calling different subroutines that use some kind of shared variables as flags indicating which Topic/ are we currently in, and which links are we looking for when parsing through ExternalPages. Unless both of your Topic/ and ExternalPages/ are randomly intermixed (very very very unlikely) and if they are - then you are really screwed :) 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: Errors on processing 2GB XML file by using XML:Simple
On Mon, May 16, 2005 at 01:33:15PM +, Nan Jiang wrote: While I think Topic/ and ExternalPage/ are not randomly intermixed as Topic/ nodes are generated in relevant categories such as Arts/ - Arts/Movie - Arts/Movie/Title and then if the Topic/ has link/ children which means it is a final category, then ExternalPage/ nodes appeared immediatly below the Topic/ with the same order as link/. The problem is that you completely misunderstood the idea of XMLtwig. You parse as you go. Here is the code that gives somewhat similar to your output. Don't get surprised by the -simplify I use to deconstruct twigs - I am just used to it and it is merely a matter of style. You can very well use parent firstchild att and family. And remember - when working with XML::Twig Data::Dumper takes a whole new meaning :) #!/usr/bin/perl use warnings; use strict; use XML::Twig; my $xml = 'RDF Topic r:id=Top catid1/catid /Topic ExternalPage about= topicTop//topic /ExternalPage Topic r:id=Top/Arts catid2/catid /Topic Topic r:id=Top/Arts/Movies/Titles/1/10_Rillington_Place catid205108/catid link r:resource=http://www.britishhorrorfilms.co.uk/rillington.shtml/ link r:resource=http://www.shoestring.org/mmi_revs/10-rillington-place.html/ /Topic ExternalPage about=http://www.britishhorrorfilms.co.uk/rillington.shtml; d:TitleBritish Horror Films: 10 Rillington Place/d:Title d:DescriptionReview which looks at plot especially the shocking features of it./d:Description topicTop/Arts/Movies/Titles/1/10_Rillington_Place/topic /ExternalPage ExternalPage about=http://www.shoestring.org/mmi_revs/10-rillington-place.html; d:TitleMMI Movie Review: 10 Rillington Place/d:Title d:DescriptionReview includes plot, real life story behind the film and realism in the film./d:Description topicTop/Arts/Movies/Titles/1/10_Rillington_Place/topic /ExternalPage /RDF'; my %want_links; my $parser = XML::Twig-new ( twig_handlers = { 'Topic' = \_topic_handler, 'ExternalPage' = \_links_handler }, ); $parser-parse($xml); #parse XML data exit 0; sub _topic_handler { my ($twig, $child) = @_; my $topic = $child-simplify (forcearray = 1); if ($topic-{link}) { %want_links = map { $_-{'r:resource'}, $topic-{'r:id'} } @{$topic-{link}}; #generate hash 'link_name' = 'directory' } else { %want_links = (); #reset the hash since we are working on a new topic (no more external links) } $twig-purge; } sub _links_handler { my ($twig, $child) = @_; my $ext_page = $child-simplify (forcearray = 1); if ($want_links{$ext_page-{about}}) { #chdir $want_links{$ext_page-{about}} #commented out since I don't have that dir print join (\n, $want_links{$ext_page-{about}}, $ext_page-{'d:Title'}[0], $ext_page-{'d:Description'}[0], ); print \n\n; } $twig-purge; } -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Time::localtime help
printf(The current date is %04d-%02d-%02d\n, $now-year+1900, ($now-mon)+1, $ now-mday); It outputs the date in such a format: The current date is 2005-05-16. I would like the name of the month(ex. 'May') displayed instead of 05. What is the easiest way to do this? The most most easiest is to create your own dictionary: my %month = ( 0 = 'Jan', 1 = 'Feb', 2 = 'Mar', 11 = 'Dec', ); and then access it from $month{$now-mon} 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: Errors on processing 2GB XML file by using XML:Simple
I keep receiving virtual memory error and program runtime error while using XML:simple to process a 2GB XML file on Windows 2000. I have changed virtual memory to 4 GB but still no use, so I wonder if anyone could offer some help? Or is there any better module to process a 2GB XML file? XML::Twig is your answer. Very clear documentation and examples. Enjoy -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Create Excel spreadsheets
I am about to start on a project that will be creating various excel files. Cpan yields quite a number of posibilities, among which Spreadsheet::WriteExcel looks most promising. I just wanted to hear some opinions on the best tool for the job before I delve into a certain inetrface. The resulting files must have multiple workbooks and be able to contain embedded images. The rest (numbers, text formatting) seems trivial through any interface. All thoughts/suggestions appreciated. 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: The last element
On Sat, May 07, 2005 at 04:13:12PM -0700, amr wrote: How can I call the last element in the array? I try the pop and it does the job but I think there is another way? If my @a = (1, 2, 3, 4); then: my $last = pop @a; is the same as my $last = $a[-1]; and pop @a; my $third = pop @a; is the same as my $third = $a[-2]; The negative sign in front of N means go N positions towards the start of the array from the end. Peter -- 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 follow a Java script link
On Thu, May 05, 2005 at 11:40:52AM -0500, Sergio Ulises Sanchez Buelna wrote: Hello all I am trying to harvest a set of information from a search service that gives the results of the search by pages. I am interested in ALL of the results. I can activate the search and obtain the first page with results. but when I try to follow the link for the next page I cant do it since the link is a Java script code at the source. I am using a WWW::Mechanize agent to do this procedure and i have tried $link = $mech-find_link (text, mytext) $link = $mech-find(textregex, qr/myregex/i).etc then $url = $link-url() and finally $mech-get ($url)the code does not work not because I am not able to get the link but because the link calls a Java script argument which is then interpreted to generate the next page. I have also tried the following methods from the WWW::mechanize module follow_link (this one does not work for the same reason presented before) and clik_button (this one does not recognize the link as a valid button) non of them work The link points to this code javascript:mySubmit( 2, 're_search', 25) on this reference a href=javascript:mySubmit( 2, 're_search', 25) previous/a Unfortunately everything is pretty much as Branislav described it - you have to reverse engineer the java script and make your own perl program behave just like it (mostly spitting back the right cookies). I went a long way some time ago to be able to login into a certain site that was entirely java navigated (took me about 1 week to develop and another to fully debug and test). Nevertheless the thing works like a charm ever since. If you are interested this is the discussion on the matter with the resulting code at the end: http://www.issociate.de/board/post/180487/WWW::Mechanize_java_navigation.html Peter -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
propagated error reporting
Hello everyone, I once again have a broad question about implementing a certain capability. Consider we have the following: main program - uses modules A B | | execute exported sub from A (A uses C D) | | | execute exported sub from C | | | execute exported sub from D | execute exported sub from B Both C and D are expected to return a value (an array for say) and then all of those will be passed to B for some more crunching and the result gets spit out back to main. I am passing only one structure around per every execution so I figured objects are out of question. However before I invoke B I need to make sure that C and D completed without warnings and if they did have any - change the behavior of B slightly. What I did originaly was return ([EMAIL PROTECTED], [EMAIL PROTECTED]) from each C and D, check if data is present, otherwise die, and then check if warnings is present and do necessary adjustments. While this works for the above, it does not scale too well, and when I started adding E, F, G, H and so on, reaching down more and more levels, it bacame very error prone. I looked on CPAN for general error reporting mechanisms but only came up with Carp (which from my understanding is more of a debugging tool for real warnings and exceptions) and Error (which looks like an overkill for what I want to have). I started thinking to implement a simple module (ErrorReport.pm for instance), have it export methods 'error' and 'warning' which will take a string and stuff it in the corresponding internal array. Then use this module in each of my modules which mught want to say something, and then have another function to retrieve everything we have so far at the point between A and B (or make the variables global with use vars/our and access them directly by @ErrorReport:: for that matter). Internally I was going to use caller() to record the whistleblower alongside its message. My question is - is this too simple to be true? I suspect this is probably not thread-safe (not that I know much about threads anyway), but are there any other obvious shortcommings that I am missing? Maybe there is a well developed framework to handle problems like mine and I am reinventing the wheel due to lack of knowingbetterness? I would appreciate any comments/suggestions/reading references. Thank You 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: REGEXP removing - il- - -b-f and - il- - - - f
I think really good programmers write nice readable programs (scripts), so begginers should understand that sooner. I think, that's why better using or instead ||. Come-on guys! Read your mails. John Krahn spent the time to write a wonderful explanation why || simply DOES NOT WORK when used with open (although it works for the general case, which does not constitute the term 'works'). Don't lure beginners into thinking this is a matter of style (like I used to think myself). There is a very rigid logical explanation behibd it, and whether you are a beginner or not doesn't change the facts. Peter -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Question about || (was REGEXP removing - il- - -b-f and - il- - - - f)
also or die is more preferable than || die Why is that? :) I was actually going to post a question about ambiguity syntax later, but here it is anyway. Are the following 4 equivalent? 1) if ($b) { $a = $b; } else { $a = $c; } 2) $a = $b or $c; 3) $a = $b || $c; 4) $a = $b ? $b : $c; Also there was an example on the web that completely threw me off. Although this works: local ($/); ,I have no idea how it undefs $/. Points to a good reading on the subject are equally appreciated. 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: Question about || (was REGEXP removing - il- - -b-f and - il- - - - f)
On Wed, Apr 27, 2005 at 09:06:39AM -0500, Peter Rabbitson wrote: Also there was an example on the web that completely threw me off. Although this works: local ($/); Sorry about this last one, I undrestand the idea of local for globs, I just thought that local $/; and local ($/); differ. While reading your answers I realised that it's the same as saying: my ($a); which is equivalent to my $a; It is pretty weird to have equivalent operators ( 'or' / '||' ) with different precedence. I guess this is where TIMTOWTDI bites back really bad... learning something new every day :) -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
bulky regex
Hello everyone, This is the first time I was able to get a complex regex actually working as I expect, but I wanted someone to comment on it, in case I am overlooking something very major. I am trying to throw away a certain string out of random text. The occurences might be as follows: Free UPS Ground Shipping rest of string some of string free ground shipping !! rest of string some of string free UPS ground shipping!!! and all variations of the above. Here is what I did: description =~ s/ #take away free ground shipping text (?: #non-capturing block for | inclusion (^) #start of string | #or (?=\S) #lookbehind non-space character ) \s* #maybe some spaces free#word 'free' \s+ #at least one space (?:ups\s+)? #non-capturing 'ups' with at least one trailing space ground #'ground' \s+ #spaces shipping#'shipping' \s* #maybe some spaces !* #maybe some exclamation marks \s* #maybe some more spaces (?: #non-capturing for | inclusion ($) #end of string | #or (?=\S\s?)#lookahead non-space character maybe followed by a space (I want to keep the space if I am cutting from inside a string) ) //ixg; #replace with nothing Seems to be working, but I am afraid it will bite me later. Appreciate any comments. The reason I placed all the (?: ) is to speed it up at least a bit, I remember reading somewhere that it matters. 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: bulky regex
On Wed, Apr 27, 2005 at 12:16:05PM -0500, Peter Rabbitson wrote: description =~ s/ #take away free ground shipping text (?: #non-capturing block for | inclusion (^)#start of string | #or (?=\S)#lookbehind non-space character ) \s* #maybe some spaces free #word 'free' \s+ #at least one space (?:ups\s+)? #non-capturing 'ups' with at least one trailing space ground#'ground' \s+ #spaces shipping #'shipping' \s* #maybe some spaces !*#maybe some exclamation marks \s* #maybe some more spaces (?: #non-capturing for | inclusion ($)#end of string | #or (?=\S\s?) #lookahead non-space character maybe followed by a space (I want to keep the space if I am cutting from inside a string) ) //ixg; #replace with nothing Ops. (?=\S\s?) above should be (?=\s\S), if it's not at the end of a string I am guaranteed at least a single space, sorry about that. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: bulky regex
On Wed, Apr 27, 2005 at 01:31:08PM -0400, Jay Savage wrote: Don't make things so complicated. You want to find some words and replace them with nothing. You don't care where in the string the pattern appears. Therefore, you don't have to predict where in the The word 'ups' is not mandatory - it might be there, might not. Also the amount of spaces inbetween is not fixed. However what you said about me not caring where the string is - you are right. I dropped (?:(^)|(?=\S)) from the front, and it produces identical results. 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: bulky regex
On Wed, Apr 27, 2005 at 01:50:57PM -0400, Jay Savage wrote: You can drop the stuff from the end, too. If 'ups' is optional and the spacing is variable, then of course handle that with * $description =~ s/\s*free\+(?:ups)*\s*ground\s+shipping\s*[!]*\s*//i; # or /ig if needed Rearrange to suit. But the imporant thing here is to go for what you need to replace, and not what you don't. Mmm... as I wrote in the comments in the very first e-mail: blablabla...I want to keep the space if I am cutting from inside a string Is there a way to do this without the lookahead? Yes I can replace with / /, but then I am introducing more spaces than there were if I am at the beginning or at the end...? Excuse my curiosity :) -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Feed Net::FTP an in-memory file
Hello everyone, Very simple: I need to generate a file and upload it to ftp. Currently I am wrapping the file together, writing it out to a temp file on disk, calling $ftp-put($tmp_file) on it, and unlinking it. Is there a way to skip the write to disk? The put() method seems to expect a path only, rather than a filehandle 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: Feed Net::FTP an in-memory file
On Thu, Apr 21, 2005 at 10:56:16AM -0500, JupiterHost.Net wrote: Peter Rabbitson wrote: Hello everyone, Hello, Very simple: I need to generate a file and upload it to ftp. Currently I am wrapping the file together, writing it out to a temp file on disk, calling $ftp-put($tmp_file) on it, and unlinking it. Is there a way to skip the write to disk? The put() method seems to expect a path only, rather than You'd use stor/write/close: my $stor = $ftp-stor($new_file_on_ftp_server); $stor-write($new_file_guts, length($new_file_guts)); $stor-close(); See `perldoc Net::FTP` for more info HTH :) Lee.M - JupiterHost.Net E... This looks a little complicated. I mean I would have to get size of the string in question and the data is utf8, meaning more headaches. Or I simply don't know how to do it which leads to the same result :) Nevertheless I somehow overlooked the part in the documentation where it says that put() takes a filehandle as well: open (VIRTUAL, ':utf8', \$data); $ftp-put (\*VIRTUAL, $conf-{target_tsv}) or die 'Could not upload file' $ftp-quit; close (VIRTUAL); Works like a charm. 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
PDF::API2
Hi everyone, Today I am stuck with PDF::API2. Although seeming very powerful, the module documentation is horridly lacking. I was able to figure a great deal of what I need by directly examining the source, however some issues are left unsolved: 1. Is there a way to get the (x,y) pos and maybe more attributes of an already processed object? I looked all over the place - doesn't look like there is such a function. Even if I put every single line and dot into a separate handler - the dump of the structure still does not yield anything. I need this to be able to do background hilighting - e.g. I placed some text through handler $some_text, I pass it to the subroutine, it extracts the starting position, the alignment and the width of the text and creates an ellipse behind it with a certain fillcolor. I actually have more uses for that, but this is the main one. 2. I don't really understand the entire concept of objectifying content elements - I can have a $paragraph object handler and use -text in conjunction with -nl to write out an entire paragraph, or I can make a separate handler for each line - the output doesn't seem to change. In this case - why the need/possibility for separate handlers? 3. Is there a difference between methods -gfx-textlabel and -text ? I understand they have a different syntax but they seem to do the same thing in the end. 4. Is there vertical alignment for text? Or the font is always centered between the zone denoted by -lead ? I have seen questions about PDF::API2 on this list before, and here and there people were suggested to try other modules. Unfortunately PDF::API2::Lite has 0 documentation and PDF::Report does not seem to be able to do all the graphics that I would eventually need in my case. So I am stuck with the vanilla API2. Any help/comments/and most importantly references to somewhat complete documentation/examples would be appreciated. Thank you 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: Match a pattern
On Tue, Apr 19, 2005 at 03:32:22PM +0300, Offer Kaye wrote: On 4/19/05, lio lop wrote: I need to print the text between two words that are in different lines. If you have: This is a nasty, multilined chunk of text and you want to get everything between ',' and 'of' you would do =~ m/,(.*?)of/s which finds the first occurence of ',' takes every character (.) including newlines (s modifier at the end) until it sees the first 'of' (made non-greedy by ?) and will return everything in $1 (capturing set of ()s ). Hope this helps 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: multidimensional arrays
$array[0] = split(' ','apples trucks'); this is equivalent to: my @tokens = split(' ','apples trucks'); $array[0] = scalar @tokens; Thus you get 2 which is the size of the array returned by split, which you are not retaining by any means. What you want to do is this: @{$array[0]} = split(' ','apples trucks'); which will correctly treat the first element of @array as a reference to another array and fill it with whatever list data split provided. Hope this helps 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: RE unfriendly error
brackets; it does not _capture_ 3 times. Only literally present/countable brackets capture. Geee... I guess you are right :) Furthermore the following works without complaining about ?: perl -e print 'ouch' unless ('123456-123256' =~ /^(\d{2})(\d{2})(\d{2})(?:-(\d{2})(\d{2})(\d{2}))?$/ ); I guess I went a little overboard with TIMTOWTDI :) 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 unfriendly error
I am getting this: [EMAIL PROTECTED]:~$ perl -e '123456-123456' =~ /^ (\d{2}){3} (?: - (\d{2}){3} )? $/x ? print 'yep' : print 'nope'; Panic opt close in regex m/^ (\d{2}){3} (?: - (\d{2}){3} )? $/ at -e line 1. Google does not turn much if anything about this error... Why is this happening? If I remove ?: everything goes well but it defies the idea of the exercise to get an optional 3 pair set of digits parsed as $4 $5 $6 in the same pass as $1 $2 $3. 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: How can I take subarray without second array (drop other elements)?
don't want to use second array (they are can be very big). After print I don't need @array anymore. Erm... if you really don't need the array anymore, why don't you just deflate it by splicing on itself? @array = splice (@array, N, 100); 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: How can I take subarray without second array (drop other elements)?
But this operation means copying an array? Even at return the result from function. And if the array and/or length are very big, it will take a long time and CPU usage. Or I am wrong? The gurus will correct me, but as far as I understand we do a splice on the initial array, take 100 elements out, deflate the indexes and return those 100 elements in anonymous array which then gets assigned in the same memory cell as the original array deflating the index to 100 and assigning the new values. I don't believe there is an intermediate copy of the array anywhere in memory, but I might be very wrong :) -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: datetime comparisons
On Tue, Apr 05, 2005 at 04:12:31PM +0300, John wrote: hello all i am wondering a there is a module that do comparisons between two different datetime stamps for example 2/4/2005:15:20:20 and 4/4/2005:12:09:23 which date is bigger (namely earliest) I was down this road some time ago myself - definitely DateTime by Dave Rolsky. While it is not the most compact and not the fastest solution it has it all. Saved me way too many time from reinventing the wheel. On the other hand if your application is rather small and is guaranteed to stay small (which is usually not the case) you might look into other possibilities like simple numerical acrobatics with Time::Local (e.g. converting everything to epoch seconds and working from there). -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: modules - lost again
Examine your concept of reside in. You appear to be confused with modules that use the Exporter. You don't. I believe you'll find that you use SomeOther::Module *before* using Configuration in the main program, which means that the assignments haven't taken place yet. A-ha! Some days I am dumber than other days :) Everything was exactly as you described. In this light I have a couple of additional questions. This one is about my Tools.pm which uses Exporter and delivers a set of 5- 10 line subroutines for stupud tasks (number rounder, strip commas from numbers, commify them back, customized html entity decoder etc etc etc). What I am currently doing is automatically exporting ALL these subroutines (using fairly descriptive names to avoid clashes) and use Tools; in all modules that might benefit from them. Pretty standard. However I do not understand if importing just a subset of just the necessary functions is beneficial in terms of speed. What I am thinking is that since every single function IS going to be used sooner or later by at least one of the modules, and since EVERY module is called at least once from the main program over its runtime - the entire Tools.pm is being processed anyway and wether I import all functions or just a few makes no difference on the entire picture. Or am I wrong? And if I am, and specifying explicit imports for each module is beneficial - is Autoloader applicable to this situation? I've seen tons of examples of how OO can benefit from calls to non-existent instances, but I didn't see a single usage of Autoloader in a non-OO envirnoment which leads me to believe that it is not applicable. Thank you. 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: modules - lost again
And if I am, and specifying explicit imports for each module is beneficial - Not for reason of speed. For reason of maintainability. You should only import names you are going to use, and then do so explicitly, so that a maintenance programmer doesn't look at the program wondering where thunk_widgets() has come from. The exceptions to this rule are few and far between. Yep... this says it right there, and makes perfect sense. I am glad I asked before I converted what I have so far to modules. Thank you! Peter -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
modules - lost again
This is to extend my question earlier about modules. Most of the OOP concepts are very nicely explained in perlboot kindly pointed out by Japhy (thank you!), however I stumbled against a problem. I don't know if I am not looking at it correctly, or the idea I want to implement is entirely ill. The project I am working on get's data from many sources and has to login here and there. I have a processor engine for each place but so far all the variables (usernames, passwords, urls, etc)are specified in the corresponding module. I will have to extend the entire thing pretty soon and there will be just way too many places to look for variables in case something needs to change so I decided to create a central Configuration.pm which will hold different hashes with configuration sections e.g.: package Configuration; %Configuration::auth = ( y_stores = { 'tb' = { name = user = pass = sekkey = }, }, mmv = { 'tbt = { user = ... pass = ... merchant_num = ... }, }, ); %Configuration::pt_accounts = ( cc_fees = { cash_account = ... gateway = ... 4 = ... 5 = ... 6 = ... 3 = ... }, ); ... You get the idea. Now I am able to access them from Main by doing: use Configuration; my $whatever_reference = $Configuration::auth{mmv}{tbt}; however if in main I have another module: use SomeOther::Module; then from within this module the same variable returns undef. I suspect I can not do this since the scopes differ, but I am using fully qualified variable names. Another way would be to use Configuration in the very same module, however then Configuration.pm got to reside in the main dir AND a copy in ./SomeOther/... I am lost. Is what I am trying to do even right from a good programming point of view? Probably the total amount of modules accessing these Configuration variables will be around 10. I would highly appreciate any input on this. Thank you Peter -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Win32::Setupsup menu item enumeration
Hi everyone, I got stuck with the inability of Setupsup::EnumChildWindows or Setupsup::GetWindowProperties to generate a list of available choices in a regular menu (the one you get when you do 'open file' for example). I do not know a thing about MFC, and perl/windows integration is not as well documented as it could have been. So here is my situation - I have a list of 5 items in this menu box. The highlight is placed on the item which was opened last - hence it is arbitrarily random. This can be somewhat avoided by sending an excessive number of UP arrows that will make sure I am at the first one and then do the descend of N steps. However it is possible that in the future the amount of items will change (e.g. 6 or 7 or even more) which will render the subroutine useless unless new values are plugged in for each items position. So the question is if there is a way that I am overlooking to dump the entire list in an array. Then finding the index of the text in question and descend index times from the top and then hit enter would be trivial. I am attaching a piece of code and the output it produced - maybe it will help someone to give me a better answer: Thank you Peter #=== Code # $active_window is the handle of the main window of the app # there are 4 visible fields, the upper left (company name) with # the list in question, then a directory tree next to it, two # drop down menus on the bottom, and ok, cancel, help, network # buttons on the right my @children; EnumChildWindows ($active_window, [EMAIL PROTECTED]); foreach my $win (@children) { my %prop; print ** $win\n; GetWindowProperties($win, ['menu', 'text', 'wndproc', 'classmenu'], \%prop); print Dumper (%prop); print \n; } # Output = ** 19399254 $VAR1 = 'text'; $VAR2 = ''; $VAR3 = 'menu'; $VAR4 = 1039; $VAR5 = 'classmenu'; $VAR6 = 0; ** 25821678 $VAR1 = 'text'; $VAR2 = 'Company Name'; $VAR3 = 'menu'; $VAR4 = 1090; $VAR5 = 'classmenu'; $VAR6 = 0; ** 20251090 $VAR1 = 'text'; $VAR2 = ''; $VAR3 = 'menu'; $VAR4 = 1152; $VAR5 = 'classmenu'; $VAR6 = 0; ** 22610276 $VAR1 = 'text'; $VAR2 = ''; $VAR3 = 'menu'; $VAR4 = 1120; $VAR5 = 'classmenu'; $VAR6 = 0; ** 15598048 $VAR1 = 'text'; $VAR2 = 'Directories:'; $VAR3 = 'menu'; $VAR4 = 65535; $VAR5 = 'classmenu'; $VAR6 = 0; ** 18612702 $VAR1 = 'text'; $VAR2 = 'z:\\ph77px~s'; $VAR3 = 'menu'; $VAR4 = 1088; $VAR5 = 'classmenu'; $VAR6 = 0; ** 23069314 $VAR1 = 'text'; $VAR2 = ''; $VAR3 = 'menu'; $VAR4 = 1121; $VAR5 = 'classmenu'; $VAR6 = 0; ** 15401522 $VAR1 = 'text'; $VAR2 = 'List Companies of Type:'; $VAR3 = 'menu'; $VAR4 = 1089; $VAR5 = 'classmenu'; $VAR6 = 0; ** 2359640 $VAR1 = 'text'; $VAR2 = ''; $VAR3 = 'menu'; $VAR4 = 1136; $VAR5 = 'classmenu'; $VAR6 = 0; ** 21299780 $VAR1 = 'text'; $VAR2 = 'Drives:'; $VAR3 = 'menu'; $VAR4 = 1091; $VAR5 = 'classmenu'; $VAR6 = 0; ** 20120036 $VAR1 = 'text'; $VAR2 = ''; $VAR3 = 'menu'; $VAR4 = 1137; $VAR5 = 'classmenu'; $VAR6 = 0; ** 27328916 $VAR1 = 'text'; $VAR2 = 'OK'; $VAR3 = 'menu'; $VAR4 = 1; $VAR5 = 'classmenu'; $VAR6 = 0; ** 20644394 $VAR1 = 'text'; $VAR2 = 'Cancel'; $VAR3 = 'menu'; $VAR4 = 2; $VAR5 = 'classmenu'; $VAR6 = 0; ** 22938002 $VAR1 = 'text'; $VAR2 = 'Network...'; $VAR3 = 'menu'; $VAR4 = 1037; $VAR5 = 'classmenu'; $VAR6 = 0; ** 18219564 $VAR1 = 'text'; $VAR2 = 'Help'; $VAR3 = 'menu'; $VAR4 = 9; $VAR5 = 'classmenu'; $VAR6 = 0; -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Uniq from array ?
Not that I see why this came up in the first place... outraged rant! How funny... By very same talking you can bring a gun to a social meeting and 10 minutes later yell Huh?! WTF did this come from?!. Anyway my 2c - I myself use the unix.org.ua archives quite a bit, which does not prevent me from owning hard prints of the Cookbook, the Pocket Ref and recently Object Oriented Perl. It however prevents from owning 2 pcs of each of those not-so-slim books so I could equally easy refer to this or that at work and at home. Michael made a solid point - he found it via google. If you want to be such a purist - why not contact google for indexing obviously stolen content? Or why not go further and sue the guy who invented OCR (I believe he is still alive and in good health). Throw in a lawsuit against Frauenhofer Institute along the way. Excuse my harsh tone but the entire thread sounds too DMCA-ish, in other words: We will place content all over the place in the most easily accessible form and we will make sure we rip you off for each and every instance of it (maybe repeatedly after Fritz takes off). And Don't you dare to complain! since we will be waiting for you at the nearest courthouse. /outraged rant! Peter P.S. Probably this is not much perl related... I apologise for me stirring up this thread. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
simple server app
Hi everyone, Here is my situation. I have a windows system which continuosly runs a perl script, which utilizing Win32::Process and Win32::Setupsup is controlling a windows only app and when triggered makes it spit export files to a samba network share. From there on my main process which runs off a CGI under linux uses those files for internal purposes and so on and so forth. I would like to be able to trigger all exports remotely from the linux machine. In order to do this I need to communicate 4 strings to the process running on the windows machine. No information should be returned back, except maybe a 0/1 flag signifying failure/completion. I looked into SOAP and since I am not running Apache or IIS or anything else on the windows box for increased stability I started thinking about something like SOAP::Transport::TCP (not much docs to look at unfortunately). It seems to be able to do the job, however I feel it is an overkill for communicating 4 strings one way and 1 string the other way... I would appreciate if more seasoned programmers share suggestions on how would they approach such a problem (maybe there is something way simpler than SOAP that I simply do not know about). Thank you Peter -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Module questions (perhaps a module creation mini-tutorial)
Hello list, I am trying to make my own modules for some tasks, and I am trying to grasp the basics before I go any further. Here is a dumb test module that I wrote just to see how things are done - it takes an array of 3 values and adds them together, returning the values on request. ### 3-element-array-calc test module (CalcTest.pm) package CalcTest; use warnings; use strict; my @collect; 1; sub new { my $class = shift; my $self = {}; @collect = (0,0,0); bless $self, $class; return $self; } sub add { print (shift @_); if ( (scalar @_) != 3) { return undef; } my ($var0, $var1, $var2) = @_; $collect[0] += $var0; $collect[1] += $var1; $collect[2] += $var2; return 1; } sub result { return @collect; } main perl program (test.pl) use warnings; use strict; use CalcTest; my $calc = CalcTest-new(); print error\n\n unless $calc-add (3, 4, 5); print error\n\n unless $calc-add (1, 2, 3); print join (' * ',$calc-result); print \n\n; exit 0; The thing works, however there are too many unclear issues. 1. Everytime I call one of the subroutines (methods I believe they are called?) I get a hash in $_[0] with only one value - the string name of the package I am calling. What defines the contents of this hash? Is it always just this single value pair or there might be additional values? If yes - what kind? (A reference towards *clear* documentation would be best). 2. The idea of blessing... I understand the idea, I don't understand the reason. Why does bless need an empty hash intialized for it to bless it? Isn't blessing completely symbolic? Or I actually might put something in \%self ? If I do - what does this give me? 3. The usage of my in a package - here and there I see clues that 'my' does behave differently when used in a module - is this true? Is it correct do declare a package-wide @collect and have subroutines work on this semi-global variable (global from the package point of view), so I can get results that stack-up - the addition in the above example, or the accumulation like in Text::CSV where you keep pushing data in, and then you wrap a string... you probably see where I am going. 4. If I don't define an explicit return value for a sub - is it always undef (like I would expect) or the package occasionally might decide to assign something as a return value? Btw, a disclaimer to cover my private body parts - I searched extensively enough (imho) for a good tutorial on this subject and all the docs follow same theoretical-bullshit-endeavor model without actual low level explanation. As a matter of fact I would never be able to write the above code correctly without looking at an actual source of a CPAN module (Text::CSV to be exact). Thank you. Peter -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
XML::Twig
Here goes my next question (I apologize for being such a nag). After extensive reading on XML processing technologies I figured for my application of XML files with hundreds of same-level branches XML::Twig is the answer. Note that I do not do *any* XML output - I am just and only processing interesting data from premade XML files, thus I am interested in the simplest and least resource expensive approach. I got the thing to work and all, indeed the memory footprint is a little smaller than with XML::Simple (not by much though, I still waste xml_size*4 memory while processing). The bigger question is why the code: my $objinfo_parser = XML::Twig-new ( twig_handlers = { 'Product' = \product_handler }, twig_roots = { 'Products/Product' = 1 } ); $objinfo_parser-parseurl ('http://www.3btech.net/3btech/objinfo.xml'); sub product_handler { my ($twig, $child) = @_; print ' * '; $twig-purge; } Produces all * after everything is processed, instead of printing them one by one once every product tag closes? From what I understood it crawls through an XML linearly (that's the only way anyway), and once it encounters an opening tag for anything that matches twig_roots it starts recording, once it sees the closing tag it has a complete sub-branch (twig), gives it to the corresponding handler, the handler purges it at the end of the sub and everything starts over again... However this is obviously not happening. Thanks for the input 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: WWW::Mechanize java navigation (Answer)
On Thu, Feb 24, 2005 at 12:45:01PM -0500, Peter Rabbitson wrote: Hello list. I had very good luck using the WWW::Mechanize object for various automated data collectors until I stumbled over http://www.mymerchantview.net. As you can imagine the problems begin when I do my first -follow_link after which the script blows with something about unsupported java. What can I use that would be as functional as WWW::Mechanize while at the same time compatible with the site mentioned above. It would be more than appreciated if somebody can submit along a few lines of code showing a click on the 'Log In' tab, a click on 'Continue' over at the next page and submittal of three types of authentication info on the successive screen. Thanks everyone. 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 answer my own question almost a month later, maybe someone would find this useful while googling. Since in my case relying on MSIE to do the navigation sounded like a joke, I spent a good deal of time debugging the login process with Netscape 7.2. Although the interface is way beyond retarded, there is a wonderful feature that allows you to see your current cookie jar. So basically after each screen I had to examine the cookie jar state and with some reading into the java script returned with every page I was able to reconstruct the entire login process. It works, although intermittenly at places but with the additional checks it pretty much had no failures in the past 2 weeks. Note that in real-life there is twice the amount of cookies, however with some trial and error I was able to eliminate half of them, as they were used by the client-side java applets. It would still be nice, however, if mozilla firefox could do external scripting, and parse the java properly for me without the juggling below, so the entire thing could reside worry-free on a linux box, but oh well... my $uid = uc $sources{$method}{user}; my $pwd = uc $sources{$method}{pass}; my $mch = $sources{$method}{merchant_num}; my $mmv_cookies = HTTP::Cookies-new; my $mmv_crawl = WWW::Mechanize-new(cookie_jar = $mmv_cookies); $mmv_crawl-agent_alias('Windows IE 6'); my $jsession; my $golden_cookie; my $merchnum_cookie; recertification: while (!$golden_cookie and !$merchnum_cookie) { $mmv_cookies-clear; $mmv_crawl-get('https://mymerchantview.net/mmv/Enrollment?directive=enrollUserInfoReIssue'); $mmv_cookies-scan(sub { if ($_[1] eq 'JSESSIONID') { $jsession = $_[2]; } }); unless ($jsession) { sleep 5; next recertification; } sleep 10; #those sleeps are mandatory - why... I have no idea $mmv_crawl-get(https://mymerchantview.net/mmv/Enrollment?USER_ACID=$uidUSER_PW=$pwdMERCH_NUM=$mchdirective=enrollUserConfirmReIssue;); $mmv_cookies-scan(sub { if ($_[1] eq 'JSESSIONID') { $jsession = $_[2]; } }); if ($jsession !~ /^0002/) { sleep 5; next recertification; } sleep 10; $mmv_crawl-get('https://mymerchantview.net/mmv/Enrollment?directive=enrollIdGenReIssue'); $mmv_cookies-scan(sub { if ( ($_[1] eq 'MMV') and ($_[4] eq 'mymerchantview.net') ) { $golden_cookie = 1; } }); unless ($golden_cookie) { sleep 5; next recertification; } $mmv_crawl-get('https://mymerchantview.net/mmv/Operations?directive=mmvPortal'); $mmv_crawl-get(https://mymerchantview.net/mmv/Operations?USER_ACID=$uidUSER_PW=$pwddirective=mmvAccessVerificationDIAMOND_APPNAME=MyMerchantView;); $mmv_cookies-scan(sub { if ( ($_[1] eq 'MMVMERCHNO') and ($_[4] eq 'mymerchantview.net') ) { $merchnum_cookie = 1; } }); unless ($merchnum_cookie) { sleep 5; next recertification; } sleep 10; } -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
ActivePerl repositories
I have a general question concerning module availability for ActiveState Perl. I asked on this list several month ago where to get the DateTime suite modules, and somebody pointed me to a certain repository at the University of Winnipeg. Now I am in need of HTTP::Cookies and instead being pinpointed to a certain place I would like to know is there a general routine for finding modules listed on CPAN but not available through ppm? Or is it that the win32 perl community does not have a centralized network like cpan and it is pretty much up to the good will of someone to compile a certain module and and serve it from a local server? 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: Math::BigInt
AFAIK perl will handle up to 15 (14 to be exact) precision without any helpers like Math::BigFloat. Then you just use sprintf ('%.Xf', $var) where X is the precision you want. Keep in mind that standard rounding is enforced (.4 - .5 as breakpoint) Peter Hello, My goal is to divide two whole numbers and get the results to a given number of decimals. $ perl -e 'print 2/3,\n;' 0.667 $ #!/usr/bin/perl use strict; use warnings; use Math::BigFloat; use Data::Dumper; -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Reference name
The answer to this question is probably beyond trivial but I can't figure it out. Say we have the following situation: my %hash = ( abcd = { a1 = 1, a2 = 2, a3 = 3 } ); another_nasty_sub (\%{$hash{abcd}}); How can I access the name (abcd) of the passed reference inside of the subroutine (not just the data a1 a2 etc but the actual key name)? Currently what I am doing is passing 'abcd' as a second value to the subroutine, but there got to be another way...? -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Reference name
On Mon, Mar 14, 2005 at 05:32:01PM -0800, Tim Johnson wrote: Did you try enumerating the keys of %hash? foreach my $outerKey(sort keys %hash){ print $outerKey\n; foreach my $innerKey(sort keys %{$hash{$outerKey}}){ print \t$innerKey\n; } } I guess I have to explain better: my %hash = ( abcd = { a1 = 1, a2 = 2, a3 = 3 }, efgh = { b1 = 4, b2 = 5, b3 = 6 } ); sub_call (\%hash, 'abcd'); exit 0; sub sub_call { my ($hashref, $object) = @_; print Now working on $object using values\n; foreach my $key (keys %{${$hahsref}{$object}}) { print $key\n; } } Simple enough right? What I was asking is how can I get the same result without passing 'abcd' and a reference to the outter hash, but by passing ONLY a reference to the inner hash. Actually the more I think about it the more I figure it can't be done, since references are symbolic and don't carry information about upper (or technically lower) level structures as the outer hash that contains the actual key name... Am I correct? :) If I am then comes the other question - are references memory hungry? In other words do if I pass a ref of the outter hash (which in my case is very very large) would I end up with a copy as big just for the sake of running each subroutine? If this is the case - I don't like it :) -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Reference name
And once again, you've written some round-about referencing code: sigh... I'll get it some day. As far as dereferencing with -, which I asked earlier but I never got an answer to. For example are $sources{${$batch_ref}{by_method}}{card_def} and $sources-($batch_ref-by_method)-card_def equivalent? -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: lost in multidimension
On Sat, Mar 12, 2005 at 11:12:49AM -0500, Jeff 'japhy' Pinyan wrote: On Mar 11, Peter Rabbitson said: _NASTY_SUB (\%{$batches{$current_batch}}); my %cards = %{clone (\%{$sources{${$batch_ref}{by_method}}{card_def}} )}; You've got two instances of \%{ thing_which_is_a_hashref } where you could just write thing_which_is_a_hashref -- FSCK! I never thought about it... I don't even want to think how many ugly reference/dereference pairs I've written so far. Thanks for the tip! Long live Larry Wall :) Peter -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Multiple variable initialization
Is there a quick way to initialize a number of variables at once? Something like my ($var1, $var2, $var3); but instead of having undef in all of them, let's say I want to have 1 in each. Any takers? 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: Multiple variable initialization
On Fri, Mar 11, 2005 at 12:45:10PM -0800, Wagner, David --- Senior Programmer Analyst --- WGO wrote: Peter Rabbitson wrote: Is there a quick way to initialize a number of variables at once? Something like my ($var1, $var2, $var3); my ($var1, $var2, $var3) = ( 1,1,1 ); Wags ;) but instead of having undef in all of them, let's say I want to have 1 in each. Any takers? Peter But... isn't... this... ahem... like... um... ugly? :) -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Multiple variable initialization
On Fri, Mar 11, 2005 at 04:09:12PM -0500, Todd W wrote: Peter Rabbitson [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] On Fri, Mar 11, 2005 at 12:45:10PM -0800, Wagner, David --- Senior Programmer Analyst --- WGO wrote: Peter Rabbitson wrote: Is there a quick way to initialize a number of variables at once? Something like my ($var1, $var2, $var3); my ($var1, $var2, $var3) = ( 1,1,1 ); Wags ;) but instead of having undef in all of them, let's say I want to have 1 in each. Any takers? Peter But... isn't... this... ahem... like... um... ugly? :) other than the program reading your mind, how could it be more consise? Well, this would definitely be a very neat feature, I hope Larry Wall is reading this list and is already cracking on the new Telepathy::Simple :) What I meant however was something along the lines of my ($var1, $var2, $var3... arbitrary number of vars) = 1, which obviously doesn't work, but I hoped it's only due to my lack of syntax knowledge. Peter -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
lost in multidimension
I've been writing a failry complicated data collector with structures as deep as 7 levels, and everything worked very nice for me, until I started cleaning the subroutine interfaces, so they would pass references back and forth instead of working on global vars. The following is a sample code: use warnings; use strict; my %batches = (); my $current_batch = 'abc'; push @{$batches{$current_batch}{transactions}}, { trans_num = 'a', reference = 'b', card_num = 'c' }; _NASTY_SUB (\%{$batches{$current_batch}}); exit; sub _NASTY_SUB { my ($hashref) = @_; foreach my $transaction (@{$batches{$current_batch}{transactions}}) { print join (' * ', keys %{$transaction}); print \n---\n; } foreach my $transaction (@{$hashref}{transactions}) { print join (' * ', keys %{$transaction}); print \n---\n; } } The first foreach in the sub, while using a variable from the main scope works like a charm. The second foreach, while working on the reference, gives me a warning on something that google only says will be removed as of perl 5.10. What is the actual meaning of pseudo-hashes? To me both foreach statements look identical... Peter -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response