Re: searching a whole array without using a loop
On Aug 24, 2004, at 7:48 AM, Darren Birkett wrote: OK, to be more specific, I'm using Net::Telnet:Cisco. When logged onto a device I'm using the show version command, and storing the output in an array. Each element of the array will therefore contain lots of rubbish. I just want to match certain keyword(s) to determine device type. That sounds like a Regular Expression, naturally. I guess a for loop is the closest I'm going to get. I just thought there would be a specific function for this. If you need only to find the first occurrence, John's suggestion is perfect. You could also use: use List::Util qw/first/; if (first { /test/ } @list) { # ... } If you need all entries that match grep() is the right choice, in my opinion. So then I wonder - which is more efficient. My earlier join example, or a for loop? Does it matter? Will you have 10 million or more entries in this list? Do you need the answer in microseconds? Will the results be used in the guidance system of a nuclear missile? Silly questions, I know, but often so is worrying about performance. With reasonable data on modern hardware, both will likely be faster than you blink. That's generally good enough, don't you think? My rule for optimization is, Speed it up when it gets too slow. Let me ask you a question: Which method is easier for you to understand? The answer to that is a much more noble pursuit, I think. To me, join() is for strings and we're dealing with a list. Because of that, I would use list tools: for, grep(), first(), etc. That doesn't make me right though. That's just what makes sense to me, so that's what I would use. Hope that helps. James -- 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 a whole array without using a loop
On Aug 24, 2004, at 9:14 AM, Gunnar Hjalmarsson wrote: Isn't grep() specific enough? Initially you said: $line = join(' ',@myarray); if ($line =~ /my string/) { some code } The equivalent using grep() would be: if ( grep /my string/, @myarray ) { some code } Ordinarily, I wouldn't even mention this, but since the conversation is about what is fastest... The above is pretty much the textbook perfect example of an inefficient use of grep(). The reason is that we just want to know if @myarray contains ANY /my strings/, but grep() fetches them ALL. If the list contains 10,000 entries, and the first is a /my string/, that's 9,999 lookups we didn't need. I would simply substitute List::Utils' first() in the above example, to fix this. Though again, it probably isn't broken at all. (See my speed rant in previous message.) James -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Sed-type-function
On Aug 23, 2004, at 10:50 AM, Dave Kettmann wrote: I guess and easy syntax for search and replace similar to: s/this/that/g ... Perl supports this exact syntax, so you are confusing a lot of us now... :D James -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Sed-type-function
On Aug 23, 2004, at 2:31 PM, Dave Kettmann wrote: Ok ... I'm going to try to confuse everyone again because either a) I'm dense or b) I'm asking the wrong question. Everyone can agree with option a, and I will not get mad :). Ok .. here goes again... For future reference, we prefer you submit your attempts to code up a solution, which we will then help fix. Make us feel like we aren't doing all the work. ;) I looked at s2p and it spit out 2 pages of perl code of which the sed command was a small bit of code. It is nothing major that I want to do an example is below: I'm unfamiliar with the program, but I have to say, Yuck. I want this ...: Aug 23 14:28:32 Auth.notice: (Access-Request 10.10.116.4 166 000611-011c0c): Login OK [000611-011c0c] To be this ...: Aug 23 14:25:32 (Access-Request 10.10.116.4 166 000611-011c0c): Login OK Or to make it easier, I want to take out the 'Auth.notice: ' and anything encased in []'s. Here's one simple way you might accomplish that in Perl: #!/usr/bin/perl use strict; use warnings; my $text = 'Aug 23 14:28:32 Auth.notice: (Access-Request 10.10.116.4 166 000611-011c0c): Login OK [000611-011c0c]'; $text =~ s/Auth\.notice://; $text =~ s/\[[^]]+\]//; print $text\n; __END__ Hope that helps. James -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: direct string manipulation (like in c)
On Aug 19, 2004, at 10:55 AM, Christopher J. Bottaro wrote: say i have two strings and . i want to replace characters 4-7 in the first string with the second string with an emphasis on speed. perldoc -f substring Come back if you need a bigger hint. ;) James -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: direct string manipulation (like in c)
On Aug 19, 2004, at 10:55 AM, James Edward Gray II wrote: On Aug 19, 2004, at 10:55 AM, Christopher J. Bottaro wrote: say i have two strings and . i want to replace characters 4-7 in the first string with the second string with an emphasis on speed. perldoc -f substring Egad, sorry. Java is my day job. perldoc -f substr James -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: direct string manipulation (like in c)
On Aug 19, 2004, at 11:55 AM, Christopher J. Bottaro wrote: Gunnar Hjalmarsson wrote: You can use substr() as an rvalue: substr($str1, 4, 8 - length $str1, $str2); or if the length of $str1 is given: substr($str1, 4, -4, $str2);# probably fastest i don't understand why the 3rd argument is negative. Then you didn't read the documentation I sent you the link for. ;) A negative index counts backwards from the end of the string. James -- 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 read data from and Excel File
On Aug 11, 2004, at 1:02 PM, jason corbett wrote: Do I need to have a special module to open/read an Excel spreadsheet, parse it, etc.? It's sure a LOT easier with a module. I would definitely go that way... I am trying to figure out if one is needed and what module is recommended. I went on CPAN and I saw SQL Parser, but I am not sure if this is best method. You're looking for Spreadsheet::WriteExcel and Spreadsheet::ParseExcel. Good luck. James -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Translate sed / Perl
On Aug 13, 2004, at 8:19 AM, Errin Larsen wrote: Hey guys (and gals, I imagine!), Hello. I'm really new to perl. I've been working through some beginners tutorials and now I need (want!) to use perl to overhaul something I wrote in the past. I've got a script (in bash) that I use that has a particular sed command in it. The command is as follows: sed -n '/System Temperatures/,/==*/p' FILENAME Here's the Perl equivalent: perl -ne 'print if /^System Temperatures/../^==/' data.txt The only tricky thing in there is the .., which is the range operator. When called in scalar context, as it is here in the if conditional, it returns true when on a line between (inclusive) the two expressions. Hope that helps. James -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: PERL and Mobile Devices.
On Aug 10, 2004, at 3:35 PM, JupiterHost.Net wrote: I remember hearing some cell phones had perl and maybe PDA's??? Really? I would be very interested to know what cell phone that is... Perl has a pretty big overhead compared to what mobile devices offer. I've seen ports for Windows CE and the Sharp Zaurus, but I wasn't aware of any others. James -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Trying To write a script
On Aug 9, 2004, at 9:05 AM, Singh, Harjit wrote: I am trying to write a script that would be able to read a file. The file is broken into number of segments and each segment starts with a similar string pattern of following type: 2.2.x.y.z: followed with white space, where x, y, z numbers change throughout the file. The segment further has number of things that I am looking for. I want to be able to capture the segment value in addition to other things in a specific segment. What is the best approach to be able to make this possible? I have tried number of things but have not been able to capture the right regular expression to capture the information. I would appreciate if any one can send in their response... Show us a few lines of data, please, and the expressions you have tried. We'll walk you through why they aren't working and give some pointers. James -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Assignment for Perl Class- hurting my brain
(Let's keep our discussion on the list, for all to help and learn.) On Aug 8, 2004, at 11:08 PM, William Paoli wrote: The field format of the file is structured like this: Car Number:Driver Name:Sponsor:Owner:Crew Chief:Car Make:Mini Biography:Team Name I couldn't tell, are you struggling with this part? Yes actually I think I am. Am I on the right track with: sub load_data_file { open FILE, winstoncup_2002_drivers.txt; @driver_info = FILE; This slurps the entire file into the array. I assume that would be a lot of drivers. Don't you just want to walk through them one at a time? A typical line-by-line read in Perl looks something like: while (my $line = FILE) { # work with $line here... } while (@driver_info) { That says, While there are elements in the array driver_info... You aren't removing any elements below though, meaning it will always be true and thus probably an infinite loop. Again, I think you meant to deal with the file line-by-line. $obj = $Car_Number, $Driver_Name,$Sponsor,$Owner,$Chief,$Car,$Bio,$Team = split /:/; split /:/ is just short for split /:/, $_, but I don't see you setting $_ anywhere. I doubt that's doing what you expect. The assignment is another issue. I don't know what you're trying with $obj =, but I doubt you're getting what you expect there. As for the rest, use parens around your lists, so you can see they are lists: ($list, $of, $some, @vars) = split ... ; Hopefully that gives you some new things to think about. James -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Trying To write a script
On Aug 9, 2004, at 3:36 PM, Singh, Harjit wrote: The following code is what I used to check if item number could be detected for the file I sent in the earlier email. The code seems to have failed and need a advise on it.. #!C:\perl\bin\perl5.6.1 $file1 = ' C:\perl\bin\dummy.txt' ; open (INFO, $file1 ) or die Can't open $file: $1; while (INFO) { if ($test = ~ /2\.2\./d+\./d+\./d+){ In a Regular Expression, one or more digits is spelled: \d+ Hope that helps. James print $test \n ; }} close (INFO); It would be a great help if some feedback could be provided... -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Assignment for Perl Class- hurting my brain
On Aug 8, 2004, at 2:24 AM, William Paoli wrote: Im not looking to cheat, just a push in the right direction. It's hard form me to help you much, without showing code. And of course, if I use something you're teacher hasn't taught yet... Still, I'll try to give a hint or two. [snip] The field format of the file is structured like this: Car Number:Driver Name:Sponsor:Owner:Crew Chief:Car Make:Mini Biography:Team Name I couldn't tell, are you struggling with this part? [snip] An attribute is simply a key/value pair in the anonymous hash that makes up your object. The above sentence from the specification explains your problem. package Nascar; sub new{ my $obj = {}; just a key/value pair in the anonymous hash... my $obj = { Title = 'Whatever' }; $obj = {Title} =; #Is this initilizing the attribute? bless $obj; } I dont know why I am just not getting this stuff. Please help me. I hope that helps go forward again. Good luck. James P.S. Never any shame in asking the teacher for some one-on-one help. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: finding out what is uninitialized
On Aug 3, 2004, at 9:12 AM, Gunnar Hjalmarsson wrote: where the @fund_array is defined by : push(@fund_array,$cat_key\|$title\|$url\|$code\|); If that's the only way @fund_array gets populated, there is no way it can contain undefined elements. Is the warning pointing to the push() line though? One of those variables could be undef. James -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Unusual Exporting
I have a module that needs to export a hash and a subroutine. I used Exporter and that's now happening, but there's a catch... I need the subroutine to make changes to that hash, when called. (I'm aware this is an unusual interface and I do have good reasons for wanting to do it.) I can't seem to get this part right. I'm using something like: #!/usr/bin/perl package MyExporter; use strict; use warnings; use Exporter; our @ISA = 'Exporter'; our @EXPORT = qw/ %hash routine /; our %hash = (Test = 'Works!'); sub routine { my($caller) = caller; $$caller::hash{Another_Test} = 'Doesn\'t work!'; } 1; __END__ When I use Data::Dumper from the module using the example above, I get: $VAR1 = { 'Test' = 'Works!' }; I'm confused about why the above doesn't work. Exporter isn't somehow creating a lexical variable out of that hash, is it? I guess this is my first question: What am I not understanding about the above? Second question: What is the correct way to do what I'm trying to do? Thanks for your time and any tips you can pass on. James -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Unusual Exporting
Sorry to answer my own question but... On Aug 2, 2004, at 1:37 PM, James Edward Gray II wrote: #!/usr/bin/perl package MyExporter; use strict; use warnings; use Exporter; our @ISA = 'Exporter'; our @EXPORT = qw/ %hash routine /; our %hash = (Test = 'Works!'); sub routine { my($caller) = caller; $$caller::hash{Another_Test} = 'Doesn\'t work!'; Changing that to: $hash{Another_Test} = 'Now works!'; Does the trick. } 1; __END__ I'm confused about why the above doesn't work. Exporter isn't somehow creating a lexical variable out of that hash, is it? I guess this is my first question: What am I not understanding about the above? I'm still a little confused about why that works. Is it because after the subroutine is exported it's called from inside the same namespace as the hash and can manipulate it at will? Or am I just lost (quite possible)? Thanks again. James -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Perl Core
Quick question: What's the best way to find out if a module is standard in the Perl Core and if it is, when it was added? Thanks. James -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Perl Core
On Jul 31, 2004, at 11:30 AM, Randy W. Sims wrote: On 7/31/2004 12:24 PM, James Edward Gray II wrote: Quick question: What's the best way to find out if a module is standard in the Perl Core and if it is, when it was added? Check out Module::CoreList http://search.cpan.org/dist/Module-CoreList/ perl -MModule::CoreList -e1 Can't locate Module/CoreList.pm in @INC (@INC contains: /System/Library/Perl/5.8.1/darwin-thread-multi-2level /System/Library/Perl/5.8.1 /Library/Perl/5.8.1/darwin-thread-multi-2level /Library/Perl/5.8.1 /Library/Perl /Network/Library/Perl/5.8.1/darwin-thread-multi-2level /Network/Library/Perl/5.8.1 /Network/Library/Perl .). BEGIN failed--compilation aborted. Guess that leads me to the question, when was Module::CoreList added? James -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: deleting HTML tag...but not everyone
On Jul 29, 2004, at 7:52 AM, Francesco del Vecchio wrote: Hi guys, Hello. I have a problem with a Regular expression. I have to delete from a text all HTML tags but not the DIV one (keeping all the parameters in the tag). This is a complex problem. Your solution is pretty naive and will only work on a tight set of HTML, formatted as you expect it to be. I'm not saying that's a problem. If you know your HTML will stay simple, it isn't. However, if you need or even think you may someday need a more robust approach, you should check out the HTML parsing modules on the CPAN. I've done this: ^^ #!/usr/bin/perl use strict; I would add: use warnings; This doesn't do anything for you here, but it's a good habit to build. It often makes finding errors much easier. my $test=EOS; htmlheadmeta content=MSHTML 6.00.2800.1400 name=GENERATOR /headbodyfont face=Courier New size=2 =SUPER SAVING= br -product one br -product two brD -product three brdIV section=true == Br/DIV brbr/font/body /html EOS $test=~s/br/\n/ig; A little less naive might be: $test =~ s/\s*br\s*/\n/ig; Even that wouldn't catch the now common br / though. Again, use a module if this kind of thing is important. $test=~s/^[DIV](.*?)//ig; This is currently removing zero tags. You are asking for a , followed by the beginning of the string (^). That is impossible, and thus never matches. I believe you meant [^DIV]+, which means one or more non D, I, or V characters, but that won't work either for reasons you pointed out. Here's a simple fix: $test =~ s/(?!\/?DIV)[^]+//ig; That searches for a , then uses a negative look-ahead assertion to verify that a DIV or /DIV is not next, and finally grabs everything up to the next . It works on the example you provided. I know I sound like a broken record, but I must again stress how weak this is. If the HTML contains a DIV (note the space), it won't work properly. Again, parsing HTML is painful, use a module and benefit from the suffering of others if you need an intelligent solution. print $test; ^^ Hope that helps. James P.S. You can use whitespace (blanks lines and spaces) to pretty up your code a little. Your eyes will thank you. Don't worry, it's free! ;) -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Endless Loop
On Jul 29, 2004, at 9:23 AM, BOLCATO CHRIS (esm1cmb) wrote: This may be a dumb question, but why will this loop not end when nothing is entered in STDIN? STDIN is a stream. A blank line does not constitute the end of a stream. I believe your can signal an end to the stream in most terminals with control-d. If we want to check for blank lines, we can do that... print Enter Things:\n; while (STDIN) { chomp; # to remove the newline character at the end last unless length $_; # end when we see nothing print I saw $_; print I saw $_\n; # update to add newline } print The End\n; Hope that helps. James -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: sort by extension
On Jul 29, 2004, at 10:42 AM, perl.org wrote: Thanks for the detailed response. Anytime. It's easier to read that code bottom to top, so let's start with: map { m/\.([^.]+)$/ ? [$_, $1] : [$_, ''] } @input; Unfortunately I really don't find this easy to read. That's unfortunate, because I actually changed it to that because I hoped it would be easier to follow. I originally used: map { [ m/^(.+?(?:\.([^.]*))?)$/ ] } @input; when I was testing your problem, so I'll post that here just to show another approach. (You must use my lc()ed sort with this. The reason I had it that way.) This solution is more my style, but I worried a bit trickier. It avoids the if/else shorthand of ?:, but you need to at least understand that a regex evaluated in list context returns the list of all the items captured by it's execution to read it. TIMTOWTDI, as they say. One of the things I prefer about Perl is how it usually leaves me with the choice to approach problems in a way I like. James -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: sort by extension
On Jul 29, 2004, at 11:23 AM, perl.org wrote: On Thu, 29 Jul 2004 12:08:20 -0400 (EDT), Jeff 'japhy' Pinyan wrote That's why he broke it down. Is the map() really the problem, or is it the regex, the ?: operator, and the two array references? All of the above ;), but now that I think about it the map looks easiest, then ?: (which I also prefer not to use, along with unless). At least map is a word instead of a (cryptic) token. Just for the sake of completeness. COND ? TRUE CODE : FALSE CODE is generally the same as if (COND) { TRUE CODE; } else { FALSE CODE; } James -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: sort files by extension
On Jul 28, 2004, at 12:27 PM, perl.org wrote: I have a list of files I want to case-insensitive sort by extension, files with no extension appearing first. It should handle both Windows and Unix directory separators. I think I have working code, but I am interested in the various syntax for this one - there MUST be a better way than my feeble attempt: I'm never one to abuse working code, but if your definition of better has something to do with sorter, a simple Schwartzian Transformation seems to work: @input = map { $_-[0] } sort { lc($a-[1]) cmp lc($b-[1]) } map { m/\.([^.]+)$/ ? [$_, $1] : [$_, ''] } @input; Hope that helps. James -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: sort by extension
(Let's keep our discussion on the list for all to help and learn, please.) On Jul 28, 2004, at 12:55 PM, John West wrote: James Edward Gray II [EMAIL PROTECTED] On Wed, 28 Jul 2004 12:41:08 -0500, James Edward Gray II wrote I'm never one to abuse working code, but if your definition of better has something to do with sorter, a simple Schwartzian Transformation seems to work: @input = map { $_-[0] } sort { lc($a-[1]) cmp lc($b-[1]) } map { m/\.([^.]+)$/ ? [$_, $1] : [$_, ''] } @input; Thanks for the suggestion. I'm not really sure what I mean by better - seems like there are tradeoffs between readability, performance and length; mine is too long. Unfortunately I can't follow this code (I'm not a big fan of map or grep) so I probably wouldn't take this approach unless it really improves performance. Not a fan of map() and grep() or just don't understand them? I'm hoping it's the second, since the first doesn't make much sense to me. Luckily, we can fix the second. map() is generally just a shorthand for a foreach loop. You feed it a list and a chunk of processing code. It runs the code on each item in the list and spits out a list that is the results the code returned for each item. Example: my @names = qw(JAMES BOB JEFF); my @title_case = map { \u\L$_ } @names; # process each name print @title_case\n;# prints James Bob Jeff Let's apply that thinking to demystify the code I offered you. It's easier to read that code bottom to top, so let's start with: map { m/\.([^.]+)$/ ? [$_, $1] : [$_, ''] } @input; That processes each element of the array input. The processing code looks for an extension and returns a two element array (by reference) that contains the original string in the first slot and the extension in the second (or an empty string, if none could be found). Our modified list of originals and extensions side-by-side is then handed up the chain to: sort { lc($a-[1]) cmp lc($b-[1]) } Are you a fan of sort()? It works just like map() and grep(). You feed it a list, a condition or conditions you want it sorted on and it returns the results. My condition here is simply what you asked for, by extension case-insensitively. We have our answer at this point, but not in the format expected so we feed it to one more map(): @input = map { $_-[0] } This is simply the reverse of the first map(). Where it turned everything into a two-part list (original and extension), this one returns everything to it's original format, discarding referenced arrays and extensions. The result of that final operation is then store back in the array. grep() is more a list filtering tool. Feed it a list, tell it what you're looking for, and you get just those elements back. Example: my @numbers = (104, 3, 102, 1, 100); my @small_numbers = grep { $_ 10 } @numbers; # search list print @small_numbers\n; # prints 3 1 map() and grep() are powerful tools, because they allow us to specify what work we want done. You can argue that they hurt readability in some cases, as long as I can argue that they help it in others. Eventually, when you're learning any language, you have to start picking up the slang too, so you can speak it like the pros do. Nothing wrong with that. Work with them a little and see if you can't put them to good use. I think you'll surprise yourself and hopefully, become a fan... James -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: sort files by extension
On Jul 28, 2004, at 2:26 PM, [EMAIL PROTECTED] wrote: Maybe I'm missing something but since you're doing Schwartzian Transformation already why call lc() every time? @input = map { $_-[0] } sort { $a-[1] cmp $b-[1] } map { m/\.([^.]+)$/ ? [$_, lc($1)] : [$_, ''] } @input; Good point. You're way is more efficient. James -- 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 Parameters
(Let's keep our discussion on the list so all can help and learn.) On Jul 25, 2004, at 8:09 PM, [EMAIL PROTECTED] wrote: OK i still can't figure this out, i understand what you explained but i still can't figure out why it doesn't want to write to the new file and also why it only removes the commas and doesn't replace it with the new line character, i modified the code a little but now when i run it it gives me this weird message: weird message IO::File=GLOB(0x8132fe4) You are printing an object. See below. -new code #!/usr/bin/perl use IO::File; use strict; use warnings; die Usage: script OLD_FILE, SEARCH, REPLACE, NEW_FILE\n unless @ARGV == 4; my($old_file, $search, $replace, $new_file) = @ARGV; my $open_file = new IO::File; my $fh = new IO::File $new_file; You're not checking if this succeeds any more. What if it fails? if ($open_file-open( $old_file)) { while ($open_file){ s/$search/$replace/g; print $fh; Perl thinks you want to print $fh, not print TO $fh. We need to clarify. print $fh $_; # or... $fh-print(); } $fh-close; $open_file-close; } --- Just out of curiosity, why are we using the module for this? Don't get me wrong, I love object oriented programming, but here the interface seems to have bitten you a few times and you're not saving yourself any work. Here's the mundane version: #!/usr/bin/perl use strict; use warnings; die Usage: $0 OLD_FILE, SEARCH, REPLACE, NEW_FILE\n unless @ARGV == 4; my($old_file, $search, $replace, $new_file) = @ARGV; open IN, '', $old_file or die File error: $!; open OUT, '', $new_file or die File error: $!; while (IN) { s/$search/$replace/g; print OUT $_; } close IN; close OUT; __END__ Hope that helps. James -- 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 Parameters
On Jul 26, 2004, at 6:29 PM, [EMAIL PROTECTED] wrote: Thank you very much for your help, but i have one more question, is this the way that regex works or is it something in my code, every time i try to run the script to search for a comma and replace it with a new line character (\n) it just removes the commas but doesn't replace it with a new line character. What is it replacing them with? n's? I'm betting your shell is swallowing the \, turning \n into just n. If that's true, you have to get a \ past the shell first. On my Unix box, both \\n and '\n' work. Unfortunately, that doesn't solve your problem. Because then you'll replace ,s with a \ followed by an n. You want \n translated into a newline character, as it is in Perl's double quoted strings. We could search your string for a \ followed by an n and replace it with a newline character, but that opens a another can of worms: What if you really wanted to replace with a \ and an n? Given that, we can eval() your string to get Perl's string behavior. That'll do what you want in this case, but may complicate some other cases for you, say if you're making a CSV file and want to replace with . It's all tradeoffs. Here's a simple change to eval() your string: s/$search/qq($replace)/eeg; # update your search to this Hope that helps. James -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Regex to do /match/match/replace?
On Jul 26, 2004, at 8:17 PM, Ian Marlier wrote: Hi, all -- I've got another RegEx question, a follow-up to one that I asked earlier today: Given a string that looks like this: This is a (string of words) that go together I need to turn it into this: This is a (stringofwords) that go together Which is to say, I need to match one set of characters (the parentheses) and then do a reg-ex operation on another (the spaces). Thoughts? Do you have to worry about nested parens? It's a lot easier if you don't: s{(\([^)]\))}{ my $replace = $1; $replace =~ tr/ //d; $replace; }e; Hope that helps. James -- 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 Parameters
On Jul 25, 2004, at 12:55 PM, [EMAIL PROTECTED] wrote: Another question, so far i have this script: #!/usr/bin/perl use strict; use warnings; The above two lines ask Perl to hold you to the laws of good programming. In return, you'll get better error messages and warnings about things that might not be what you intended. That's a good deal anytime, but critical in early Perl learning. Because it forces you to write cleaner code, it also helps us read your code, which again, can only help you. The biggest change these rules will hold you too is declaring your variables before you use them. In Perl, that generally looks like this: my $some_scalar;# declare a scalar my $some_scalar = 'initial value'; # declare a scalar and initialize it with a string You only have to change one line below to get the code to pass strict. Can you see which one? use IO::File; die Usage: script OLD_FILE, SEARCH, REPLACE, NEW_FILE\n unless @ARGV == 4; my($old_file, $search, $replace, $new_file) = @ARGV; $fh = new IO::File $new_file; if (defined $fh) { while(){ The above line isn't doing what you want. It walks through @ARGV, opening those files, and reading from them line-by-line. We didn't empty @ARGV with our test above, so first it will open $old_file, which is what you want. When it finishes going through that, it will try to open your $search pattern, as a file. As you can see, problems start here and you get the warning messages you mentioned. The fix is to read from only what we intend. Instead of opening just one file, open two, one for reading and one for writing. Then, assuming you open the old file in $old, you just need to modify your while loop to: while ($old) { s/$search/$replace/g; print; You don't want to print to the screen, you want to print to the new file. Hint: You need and $fh in the above line somewhere. Hopefully these tips will get you going. If they don't cry help again and I'll give more specific answers. Good luck. James } $fh-close; } But the first problem is that if i try to run the code like this: perl script.pl old.txt , \n new.txt it will remove all the commas but won't replace them with new line characters it will just remove them. Also when i try to run the script it gives me this error: Can't open ,: No such file or directory at script.pl line 11, line 1. Can't open \n: No such file or directory at script.pl line 11, line 1. Can't open new.txt: No such file or directory at script.pl line 11, line 1. Why am i getting these errors, and how can i fix this? Thanks in advance. -Original Message- From: James Edward Gray II [mailto:[EMAIL PROTECTED] Sent: Saturday, July 24, 2004 3:13 PM To: [EMAIL PROTECTED] Cc: [EMAIL PROTECTED] Subject: Re: Multiple Parameters On Jul 24, 2004, at 11:38 AM, [EMAIL PROTECTED] wrote: I am trying to write a search and replace script that can accept multiple arguments, but i want the first argument to be the filename to read, the next one to be the string to search for, the next one to be the replacement string, and the last one to be the name of the new file it creates with the new changes, but i can't figure out how to seperate each argument, can some one tell me how to do something like this. Any help is very much appreciated. Well, command line arguments come into the program by way of the array @ARGV. So first we should be sure you got the right number of arguments: die Usage: script OLD_FILE, SEARCH, REPLACE, NEW_FILE\n unless @ARGV == 4; Then we can use it: my($old_file, $search, $replace, $new_file) = @ARGV; Finally, just FYI, you can do what you describe with a one-liner: perl -pi.bak -e 's/search/replace/g' old_file Hope that helps. James -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response -- 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 Parameters
On Jul 24, 2004, at 11:38 AM, [EMAIL PROTECTED] wrote: I am trying to write a search and replace script that can accept multiple arguments, but i want the first argument to be the filename to read, the next one to be the string to search for, the next one to be the replacement string, and the last one to be the name of the new file it creates with the new changes, but i can't figure out how to seperate each argument, can some one tell me how to do something like this. Any help is very much appreciated. Well, command line arguments come into the program by way of the array @ARGV. So first we should be sure you got the right number of arguments: die Usage: script OLD_FILE, SEARCH, REPLACE, NEW_FILE\n unless @ARGV == 4; Then we can use it: my($old_file, $search, $replace, $new_file) = @ARGV; Finally, just FYI, you can do what you describe with a one-liner: perl -pi.bak -e 's/search/replace/g' old_file Hope that helps. James -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: New Line / Chomp Query
On Jul 23, 2004, at 7:16 AM, Bob Showalter wrote: On Mac systems, the terminator is something different (not sure what), but the same concept applies as for Windows AFAIK. Mac OS 9 and below used a single CR (0x0D) as the line terminator. Mac OS X is a Unix-ish system, as you described it, and thus uses LF (0x0A). James -- 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 do it do find and replace specific words using perl
On Jul 23, 2004, at 5:13 AM, [EMAIL PROTECTED] wrote: Hi All, Hello. Could some help me in doing this using perl. We will help, yes, but we probably won't write it for you. What have you tried. Where are you stuck? Show us some code. James -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: New Line / Chomp Query
On Jul 23, 2004, at 7:56 AM, Bob Showalter wrote: Thanks. Is translation to LF performed on input/output (a la Windows), or is $/ set to CR on those systems? No translation. $/ was set to CR and even \n gave you a CR. Luckily, as I said before, Mac OS X is a much more native Perl, being in the Unix family. Mac OS 9 is definitely a fading star, so it's getting less and less common to encounter it in any form. James -- 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 do it do find and replace specific words using perl
On Jul 23, 2004, at 8:14 AM, [EMAIL PROTECTED] wrote: Hi James, Hello again. I was trying this but not sure where it is going wrong ... There you go. Now I'll help... ;) use strict; use File::Copy; You import, but do not use the above module. We don't need it. my $dest_file = sendToAdapter.properties; my $searchstr = 'sample'; my $repstr= 'FileAdapter'; open(FL, $dest_file) or die(Doh - $!); $^I = '~'; I believe the above trick only works with the construct. You're using a filehandle, so it's not active. s/$searchstr/$repstr/g while FL; You are reading in the line and altering it. What you are forgetting to do it to print it back out. close(FL); Would appreciate if you could help me. I'll sure try. Here's my corrected version of your script: #!/usr/bin/perl use strict; use warnings; # a good idea, helps us find mistakes easier push @ARGV, sendToAdapter.properties; # add to @ARGV, which processes local $^I = '~'; # set inplace editing my $searchstr = 'sample'; my $repstr= 'FileAdapter'; while () { # read s/$searchstr/$repstr/g; # change print; # write } __END__ Hope that helps. James -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Problem with compiling a script
On Jul 21, 2004, at 8:35 AM, Paul Smith wrote: Dear All I am trying to run the script below, but I always get the following error: [EMAIL PROTECTED] scripts]$ secondperl Global symbol $greeting requires explicit package name at /home/paulus/scripts/secondperl line 6. Global symbol $greeting requires explicit package name at /home/paulus/scripts/secondperl line 7. Execution of /home/paulus/scripts/secondperl aborted due to compilation errors. Easy enough. The script is: #!/usr/bin/perl use warnings; use strict; Above, you are asking Perl to make you play by the Good Programmer rules. One of those rules is, you must declare a variable before using it. $greeting = World; Here you use an undeclared variable. Usually, you'll declare a variable with my, so change to above line to: my $greeting = 'World'; Hope that helps. James print It matches\n if Hello World =~ /$greeting/; -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Problem with compiling a script
On Jul 21, 2004, at 8:47 AM, Paul Smith wrote: Bingo, James! Sorry for my ignorance, but I am just beginning with Perl. Not a problem. Brand new to Perl and already using strict, you're off to the perfect start. Welcome. James -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Another Perl datatype headache ( scalars $, hashes %, and arrays @ )
On Jul 18, 2004, at 7:59 PM, gohaku wrote: Hi everyone, Howdy. after writing perl scripts for about 3 years now, I still have trouble with the basic datatypes. I know that variables that start with '$' are scalars. This covers Hashes ($HASH{$key}), Arrays ( $_[0] ), and regular scalar values ( $foobar ); Looks like you are doing good to me. The code I write as well other's code is still unreadable to me even though I have followed examples from the Camel book, many other Perl books from O'Reilly and online references. I have also used perldoc on many occasions. I'm sorry to hear that. Sounds like you are doing most of the right things. Perhaps you just need to give it some more time. There are still some things that haven't sunk in, such as: If I want to add Hash keys to another Hash, I do the following: %HASH = ( 1 = 'one' ); #NO BRACES OR ELSE %HASH2 = ( 2 = 'two' ); AGAIN, NO BRACES OR ELSE... @HASH2{ keys %HASH } = ; #confusing, considering it's the symbol used for arrays If it's confusing, let's do it a different way. for my $key (keys %HASH) { $HASH{$key} = ; } Shorter isn't always better. Use what you can understand. To get the length of an array, it's $#array, not [EMAIL PROTECTED] or #$array. Usually, I use scalar @array; $#array is not the length of the array. It is the number (#) of the last scalar ($) held in the array or more simply, the last index that has been assigned. scalar(@array) is the length and the way to go, so again I see no problem here. Problems with subroutines where the array is the first argument sub badsub() { my (@array,$scalar) = @_; #Pass Array last! #my ($scalar,@array) = @_: ... } Again, you show the fix for the problem you mention. Looks like you understand a lot more than you give yourself credit for. If you are sure your sub is called: some_sub( @array, $scalar ) You could use: sub some_sub { my $scalar = pop @_; my @array = @_; # ... } But I much prefer reversing the order, as you did above. I still don't know how to declare arrays using only '$' instead of '@' I believe you are talking about references here. They would be a good solution to the problem above. Using them you can pass 5 arrays, 3 hashes and 2 scalars to a sub in any order you like. However, they complicate things a little. If you're still having trouble grasping Perl without them, give it a little more time before running down that road. anyway, Is it possible to write scripts using only '$' instead of other prefix symbols? In other words, a php-style script written in perl Whether it is or not, it's not the answer to your problems. Start trying to make sense of the world you find yourself in. There are rules. Try to understand why things are happening, not just that they are happening. $ is for scalars. Even with $hash{some_key} and $array[0] we're talking about one entry of the group, a scalar. @ is for when we are talking about an array as a whole: my @array # create array scalar @array # get length of array @array = @_ # copy array % is similar, for the hash as a whole. For example, we don't want the keys() of one entry of a hash, that doesn't make sense. We want the keys() of an entire hash, so we call it with: keys %some_hash With sub routines, everything passed is folded into an array @_. We do that so subroutines can handle varying numbers of parameters with ease. Because of that, if we pass an array and a scalar, they are going to end up in @_ together and we need to separate them back out on the inside. We've seen different ways to do that above, and references provide yet another way. Hopefully some of this makes sense and helps get you over the hump. Hang in there. James -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Edit a file inplace..
On Jul 19, 2004, at 10:56 AM, [EMAIL PROTECTED] wrote: Hi, I am trying to edit an ASCII file in place I tried perl -pi -ne s/ERROR/TRACKED/g status.log Well, we definitely don't need -p and -n, since -p is -n plus some. and received Can't do inplace edit without backup Okay, let's try using a backup: perl -pi.bak -e s/ERROR/TRACKED/g status.log I believe Activestate Perl for Windows requires this. Hope that helps. James -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: symbolic references in perl module help
On Jul 16, 2004, at 7:54 AM, Luis Pachas wrote: Hi I have a problem, I have a PM i have this A.pm : package A; my %b; $b = { apple = \foo1, oranges = \foo2, open = \foo3 }; sub foo1 { print apples\n } sub foo2 { print oranges\n } sub foo3 { my ($item) = @_; print $item.\n } 1; ## End Module MAIN : !#/bin/perl lib $ENV/; use MOD::A; $MOD::A::b{foo1}-(); $MOD::A::b{foo2}-(); $MOD::A::b{foo3}-(pairs); exit(); Thats it, I keep getting a function undefined, I used require and exporter but I kept getting subruotine undefined...at times in the main:: and in the perl modules... I went around this by having the Hash of symbolic references in the main namespace so it works...I just need to know if PERL allows symbolic reference variables or hashs with symbolic references to be access in the Perl modules or just in the main. You're using a boat load of tricks to bypass the real problem. Why don't you show us the code that is producing the function undefined errors and let us fix that for you. James -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Pattern Matching records from a table query.
On Jul 16, 2004, at 3:46 PM, jason corbett wrote: I want to eliminate the . (periord) or , (comma) from records that I return from a query, but I cannot figure out how to approach it. Does Perl have a way that I can match a string that from an array, remove a character or characters? For example say I have array @records that contain the following: Myrecord1 Myrecord2Myrecord3Myrecord4Myrecord5, inc. Myrecord6, LP Myrecord7, LLC I want to send this query out to persons in a .csv file but the join(,, @record) statement that I am using causes the and extra cell to be created at Myrecord5, inc. Myrecord6, LP Myrecord7, LLC. How about? tr/.,//d foreach @records; James -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Help translate into Perl
On Jul 16, 2004, at 4:51 PM, Mike Blezien wrote: hello, I have been given some programming code that I need to convert or translate into perl coding, and I was hoping someone on this list maybe able to help me out. What have you tried? We will help you when you get stuck, but we won't write it for you. ;) If you need to hire a Perl Programmer, please do so. James -- 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 (from a file)
On Jul 15, 2004, at 9:40 AM, Brian Volk wrote: Hi All, If I have a file, /usr/bin/my_urls.txt which contain... urls... :-) one on each line. Can I read these into a foreach statement instead of listing them individually? I think I need to use a filehandle to open the file and then send that to the @ ... right? Exactly, right. I'll give the steps: 1. open() your file. Remember to check if it succeeds! 2. Read line by line, chomp()ing line endings and adding them to an array. 3. close() fiie and use array in foreach loop. Just shout if you need more help... James -- 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 (from a file)
On Jul 15, 2004, at 10:33 AM, Brian Volk wrote: Am I getting close...? Sure are. my $file = /Program Files/OptiPerl/urls.txt; open (LINKS, $file) or die Can't open $file: $!; We're fine up to here. chomp (@url = read(LINKS, $url, 100)); Let's break that into two steps: my @urls = LINKS; # slurp the file chomp @urls;# remove line endings Thanks for your help! My pleasure. James -- 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 (from a file)
On Jul 15, 2004, at 10:56 AM, Brian Volk wrote: James, Thanks so much for your help, it's now working great! Happy to help. One question, if you don't mind... Sure. my @urls = LINKS; # slurp the file Is this telling the diamond operator what to use for input? You got it. Because we're assigning to an array it's called in list context. The diamond operator, in list context, returns the rest of the lines of the file. This is generally called slurping. Hope that helps. James -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: not sure what I did ?
On Jul 15, 2004, at 3:34 PM, Brian Volk wrote: This script was running just fine before I changes the files in the directory handle. What I don't understand is why the file names are showing up when I run the script very confused. I'm betting that test file directory isn't the same one your code is running from. Reading the directory only gets you a name. You'll need to prepend a path, if needed. James -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: $^T inconsistant?
On Jul 14, 2004, at 2:27 PM, perl.org wrote: I would like to use them if just for documentation purposes - it is just slightly more clear to me to see sub something( $$$ ) { than sub something { In Perl, we write that: sub something { my($param1, $param2, $etc) = @_; # } James -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: $^T inconsistant?
On Jul 14, 2004, at 2:50 PM, perl.org wrote: This does kindof make me laugh though: Alphanumerics have been intentionally left out of prototypes for the express purpose of someday in the future adding named, formal parameters Sorry in advance to anyone who will inform me that's copyrighted content. I believe named parameters are coming in Perl 6. James -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: $^T inconsistant?
On Jul 14, 2004, at 3:18 PM, perl.org wrote: OK, unless I'm missing something, I will only prototype my functions, not the legacy code here. We're trying to teach you Perl. Please remember that. It's why you are here. Most of us Perl users aren't big on prototyping. As far as I'm concerned, it creates more issues than it solves. You may feel differently. Fine. It's in the language. Use away. However, the prototyping that's built into Perl really has little to do with named parameters. I'm coming into this conversation late, so I didn't see what your problem is there. We typically use paired hash-like parameters for this in Perl land. It's a good fit, we think. Flexible but powerful. If you need to validate your parameters to some criteria, please do so. If you find that too much work and only want to do it once, create a subroutine that does it for you. Move that subroutine into a module and you can use it everywhere. Throw it on the CPAN so we can too. Welcome to Perl. James -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: $^T inconsistant?
On Jul 14, 2004, at 3:39 PM, perl.org wrote: On Wed, 14 Jul 2004 15:31:00 -0500, James Edward Gray II wrote We're trying to teach you Perl. Please remember that. It's why you are here. This sure can be an unfriendly list... That was my Nice Voice, actually. Ask the list. I ran off some guy using my Mean Voice recently. Most of us Perl users aren't big on prototyping. As far as I'm concerned, it creates more issues than it solves. This is what I'm trying to understand - what issues does it create? I still don't have a real answer. Bob has already given you one. It can spontaneously change the behavior of subs. My main reason is that Perl's Method Dispatch bypasses them altogether. That makes them useless with objects and thus useless to me most of the time. Welcome to Perl. I've been programming Perl for about 10 years. I do hate the syntax and other annoyances when I return to Perl from Java or C#, but I also appreciate the flexibility. Whatever you think is fine, but remember we like Perl. ;) Be good. I hope to use this list as a forum for what I hope are best practices and to further my understanding. If I am not welcome here, just let me know. We are here to help you learn Perl. We welcome your interest as long as you continue to welcome our Perl Way answers, agree or disagree... James -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Reading a variable file name
On Jul 13, 2004, at 8:31 AM, [EMAIL PROTECTED] wrote: Greetings, Howdy. Would someone be kind enough to point me in the right direction to solve this problem? I'll sure try. An application creates XML files in a subdirectory, which I then convert to EDI. That part is now working fine. My problem is that the application creates files during the day, with slightly different names. For example: File0001.xml File0002.xml File0244.xml We can sure make a regex for that, right? m/^File\d+\.xml$/ The file names vary based on what part of the application creates them. There seems to be no pattern of the number after the alpha characters. I need to read each of these files, and concatenate them into a single EDI file. Do you know how to read the listing of files in a directory? Three steps: opendir DIR, 'path/to/dir' or die Directory error: $!; # open dir my @files = grep m/^File\d+\.xml$/, readdir DIR; # get file listing using earlier regex closedir DIR; # clean up after ourselves, as all good programmers should # loop over @files down here... The only files in the subdirectory need to be processed; and all of the files in the subdirectory need to be processed. Was that line English? laughs You lost me here. If I haven't solved your problem yet, try me again on this part. Could someone point me in the right direction? Hope that helps. James -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: sub naming conventions
On Jul 13, 2004, at 6:52 PM, perl.org wrote: Is there an established, documented best practice for naming subroutines in Perl? does it differ whether the subroutine is in a script or a module (I would like it to be clear in my scripts whether I am expecting something local or packaged). I have seen at least: some_function() This one is typical Perl style. Some of use find it easier to read than those Java-ish variants you showed. Check out: perldoc perlstyle James -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Split the line with | character
On Jul 6, 2004, at 4:09 PM, Wil wrote: Dear Folks, I'm trying to split a line that contains a pipe | and I cann't find a way how to do it. If i put a back slash \, it doesn't work either. Can somebody help me how to do it? There's really nothing wrong with your code, so the problem is something you aren't showing us. split() takes a regex to split on, so the pipe does need to be escaped. split m/\|/, $line Perhaps if you post the rest of the code we'll see other things, but first are you using strict and warnings? If not you should be. They might just lead you to the problem. James -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: __DATA__ Token Problem
On Jul 5, 2004, at 2:57 PM, Jan Eden wrote: 2. Is it possible to change to content of what the handle so that the __DATA__ Sektion of my skript changes? I don't think it's a good idea to have a script write to itself. The DATA section is meant to keep static input out of the way of your processing commands. If you want to modify it, I suggest storing it outside of the script. The above warning is excellent and VERY true, but to be complete and answer the question: Yes, it is possible. You reopen the DATA handle in read write mode. Careful though, as Jan said, Here be dragons! James -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Socket or NetServer::generic???
On Jun 30, 2004, at 3:49 AM, Bastian Angerstein wrote: Hello, there I am progarmming a client server passed solution. My Question here ist which Modul I should use. I already noticed that the IO::Socket and the NetServer::Generic are both easy to use. My question is does a IO::Socket server handle multiple clients or not? By itself, not really. To handle multiple clients you need to combine it with some sort of multiprocessing device: Threading, fork(), or non-blocking IO. These can be handled without a module, but it doesn't fall into the category you mentioned, easy to use. Just FYI, if you're going to be digging deep into networking, Network Programming with Perl is simply an excellent book. Good luck. James -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: string seperated by multiple spaces
On Jun 28, 2004, at 10:19 AM, Naser Ali wrote: Hello all, I have a line of text and numbers each seperated by multiple or single spaces looks like this abc 123 33545 789 I wanted to split the above line and store each column value in a specific variable and later print, Below is the code I am using but it's not working as I desire, $Avg=$first[$i]; chomp($Avg); ($label,$TD,$YT,$M,$L,$Y,$W)= split (/i\s*/,$Avg); print $label,$TD,$YT,$M,$L,$Y,$W\n; I used \s* in split, so I do not have worry about counting the spaces or tabs between each field Any suggestions on what am I doing wrong..? There is an extra character at the front of that regex, an i character. James -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: string seperated by multiple spaces
On Jun 28, 2004, at 11:15 AM, Naser Ali wrote: Below is the actual code. This is just the preliminary code to test the logic, it is not final yet, therefore, I am not using Warnings, Strict or for that matter anything else. It's easy to make excuses, harder to do the right thing. Help us help you. I've seen enough of your posts, these lessons should be learned by now. You START with warnings and strict, when they can help you most. I bet you would be getting warnings right now, if only you would turn them on. Then, if you followed them, you might just solve your own problem. Also I am slurrping the whole file, and I know I do not have to, but alternate ways, I ll decide later. Why? Why code it twice? Two different techniques. Just use the right one, and stop hindering your own growth as a programmer. --- -- open(TFILE, file.txt); ... or die ...; # MUST test success @first=TFILE; Not needed, and you know it. close (TFILE); for ($i=0; $i = $#first; $i++) { In Perl, we write that: for my $i (0..$#first) { Of course, you aren't even using indexes, so better is: foreach (@first) { $Avg=$first[$i]; Why? chomp($Avg); ($label,$TD,$YT,$M,$L,$Y,$W)= split (/\s+/,$Avg); ... split ' ', $Avg; If it's not working, $Avg doesn't contain what you think it does. Add a print statement before to prove it. print $label,$TD,$YT,$M,$L,$Y,$W\n; } James -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: string seperated by multiple spaces
On Jun 28, 2004, at 11:32 AM, Michelle Rogers wrote: wow..somebody woke up on the wrong side of bed, this morning... I wish I could say I was sorry. ;) You think whatever you want of me, but I'm not wrong. I've tried telling the person who started this thread before. Now I'm trying something else. I really do want to help. That's why I'm here and that's why I said what I said. It's a good lesson to all, I think. Asking us to volunteer our time to read your junk code is not a good way to make friends. James -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: string seperated by multiple spaces
On Jun 28, 2004, at 11:37 AM, MCMULLIN, NANCY wrote: After all, I thought the name of this group was Perl BEGINNERS... Sure is. And the FIRST thing beginners need to learn is to add strict and warnings to help them learn. It also helps us read your code, which can only be good for you. James -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: string seperated by multiple spaces
On Jun 28, 2004, at 11:55 AM, Naser Ali wrote: But on the other hand there are people on the list like Mr. James Edward Gray II has some ego problems. No body asked you to answer my question. if you really think beginners like me, for whom this list was created in the first place, are not worthy of your expertise and knowledge, then please by all means spare us from your wisdom and as well as criticism. You must bare mind that different people think differntly and will have different approach which must not be mistaken by polity and lazyness without knowing for sure. With all due respect, if you can't, then do not help. The world will survive without your help. I'm sorry my response offended you. I'll refrain from answering your future questions, as requested. James -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Creating images
On Jun 25, 2004, at 5:56 PM, dan wrote: Hi all, again! I'm attempting to make a web page, where all the buttons are dynamic, where dynamic I say there's 1 template button image with nothing written on it, and I want to put requests into a html page to call a script as an image to put text on top of the image, then output as 1 image. Does this make sense what I'm try to do? Is this even possible? If so, what's the best way of going about it, as I have absolutely no idea where to start on this one. I've aquired Apache::ImageMagick, but can't make head nor tail of the readme. This sounds like a HTML (DHTML or CSS or whatever) question. You would probably get better, quicker responses from a group that focus on those kinds of problems. James -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Execute a sub: $sub
On Jun 24, 2004, at 11:55 PM, Daniel Kasak wrote: Hi all. I have an object that I want to have execute some code that it gets told about when it's constructed. How do I go about that? ie: $self-{some_code_to_execute} will either have the name of a sub, or a reference to a sub, or something. I believe you can use: $self-{sub_reference}-( @params ); A name only is a soft reference and will not pass strictures, as usual. Hope that helps. James -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Printing outside of foreach...
On Jun 24, 2004, at 11:52 PM, Daniel Falkenberg wrote: Hello again, The folling code takes some data from the Australian Stock Exchage website. The problem I am having is that I need to be able to access the hash of the hash outside of the foreach statement. So in other words I would like to be able to access areas within the hash %stock_hash any where in my script. I take it I need Perl to store the hash $stock_hash into memory and remember it. Am I on the right track here? At the moment the hash %stock_hash will print exactly what I want within the foreach statement. Have you tried using it outside the loop? I suspect it will work. Unfortunately, if it does, it points to a bigger problem. You're probably not using strictures. That's a bad habit and one you want to get out of quickly. use strict; use warnings; Those two lines belong at the top of all your scripts until you understand them enough to say why they don't. Together, they represent a deal between you and perl. You promise to be a good programmer and perl promises to reward you by being a helpful compiler. That's a good deal. If you add these lines to your code and it stops working, you probably just need to declare your variables before you use them. my $variable; # declaration my @names = qw(Bob Jan Steve); # declaration with initialization Now, when you are doing this, your hash will probably stop being available outside your loop (if you declare it inside). The easy fix is just to declare it before the loop, so you can use it inside and after. Hope that helps. James -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Perl script
On Jun 25, 2004, at 2:49 AM, Jame Brooke wrote: #!/usr/bin/perl [snip code] I have few question regarding code above, 1. what the function for if ( $ARGV[0] =~ /^-([udm])$/ ) { $type = $1; shift @ARGV; } convert(@ARGV); It's grabbing the command line switches, crudely. Better would be to use the standard module Getopt::Std. 2. How i add line to the script that would print out a usage line, if wrong number of the argument are give in the script? die Usage: whatever you want to say here\n unless @ARGV; That line will check that you are passed arguments. If you want to check for a certain number of arguments, add a == # after the @ARGV. thanks, any comment. I have a few more comments. 1. I'm assuming this script converts line endings from DOS to other formats. If types u, m, and d represent Unix, Mac, and DOS, the Mac conversion is incorrect. That replacement should be: s/\r\n|\r/g; # for Mac OS 9 and below; OS X+ is Unix and uses that conversion 2. As written, the script is not portable. It probably works on DOS/Windows and Unix. It will not work on old versions of the Mac OS and possibly other platforms. To fix this, you need to replace all \r and \n characters with their escapes \015 and \012. 3. This script doesn't use strict and warnings, and it should. See my previously posted rant today in the thread Printing outside of foreach 4. Replace convert(...) with convert(...). That's how we call subs now. 5. The script can definitely be simplified a lot, if desired. That is left as an exercise for the reader... ;) James -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Printing hash outside of foreach loop
On Jun 25, 2004, at 10:12 AM, Daniel Falkenberg wrote: Hi Wiggins, Thank you for your reply. I will go and use the Finance::Quote::ASX module. For now though this problem is really bugging me and for my own sake I would like to get it to work. I have declared all my variables and am using warnings and strict. Unfortunarly I am still only able to print the last set of keys and values of my hash of hash outside of the foreach loop. Any other ideas? Yes, stop replacing the entire hash each time through the loop with your assignment. You just want to set one key. Change: %stock_hash = ( $downloaded_stocks[0] = { Trading Price = \$$downloaded_stocks[1], Price Change = \$$downloaded_stocks[2], }, ); To: $stock_hash{$downloaded_stocks[0]} = { Trading Price = \$$downloaded_stocks[1], Price Change = \$$downloaded_stocks[2], }; Hope that helps. James -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Perl and Excel
On Jun 25, 2004, at 10:44 AM, Naser Ali wrote: Hello All, Is there a way to move data from flat file to Excel spread sheet using perl? Definitely. Take a trip over to the CPAN. You're looking for the module, Spreadsheet::WriteExcel. Or, sometimes when I'm in a hurry and I don't need formatting, I just spit out a CSV file. Excel reads those just fine. Good luck. James -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: A possibly stupid 'Perl' question?
On Jun 25, 2004, at 1:25 PM, u235sentinel wrote: I haven't used it myself however I understand there is Active Perl for Windows available. I don't have any details but perhaps you could google for it or someone here could give you directions. No need to do this as it is available from http://www.perl.com/ with all the other distributions. James -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Timer in Perl??
On Jun 24, 2004, at 9:33 AM, William Martell wrote: Hello Group, Could anyone please tell me if there is a timer function in Perl. I am trying to get some perl code to run every morning, but I am unsure how to do it. You could always sleep() for a day between runs, but that seems far too clumsy. To me what you asked is a Operating System question. On Unix, I would use cron to run the script ever morning, for example. James -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Quoting a scalar in a substitution
On Jun 23, 2004, at 11:23 AM, Richard Barrett-Small wrote: Hello all, Howdy. Will really appreciate help with this: I'm pulling my hair out with this one. I have a list of contents in the @contents array and the script finds those headings in the html and adds anchors to them. The trouble is, the substitution won't match when there's a question mark in the content item: Try: m/\Qvariable_with_meta_chars\E/ The \Q ... \E construct escapes the meta characters for you so you get a literal match. Hope that helps. James -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: pattern matching
On Jun 23, 2004, at 12:34 PM, [EMAIL PROTECTED] wrote: Hi, I have a string similar to: Comment: FILING --- - This is read in as one line (with the page feed). I was trying to whatever follows the words and I tried this. Let's try to get a little simpler with our approach. Does this grab what you need? m/(\W+)$/ James -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: pattern matching
(Let's keep our discussion on the list for all to see.) On Jun 23, 2004, at 12:44 PM, [EMAIL PROTECTED] wrote: Let's try to get a little simpler with our approach. Does this grab what you need? m/(\W+)$/ James What a quick response. Thanks. No problem. I assume you mean do this? Am I right? m/(\W+)$/ s/$1//; No, I don't mean that. Perhaps I didn't understand what you needed. I thought you wanted to capture the characters after the words. Are you trying to remove them instead? If so, use: s/\W+$// That would replace all non-word characters at the end of your string with nothing, deleting them. If I'm still not getting it, try explaining your goal again. James -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: pattern matching
On Jun 23, 2004, at 12:59 PM, [EMAIL PROTECTED] wrote: OK. I am reading a file. This line is at the bottom of the file and the ---** is a sign that the section is complete. This may be a sign that you aren't reading the file in the easiest possible way. I wonder if setting the input separator to this sequence would be the way to go. Something like: local $/ = '---**'; I need to be able to pick up that line, and see if there is also code on the beginning of that line that I need to save. save( $1 ) if m/^(.+)\Q---**\E$/; So in this case I was searching for words (with colon's) and perhaps other code that precedes the and to try and discard the end of the line. (After the word FILING, there is a page break character, but it's all being read in as one line.) Is that a form feed character? Is it the only one in the file? You might be able to use that somehow. Ideas: local $/ = \f; # or ... save( $1 ) if m/^([^\f]+)\f/; # or ... my $words = (split m/\f/, $your_line)[0]; This is a sample of the line: Comment: FILING --- - That's why I tried (and failed :) with this: if (/(\w+:?\s*\w*:?)+(.*?\*+\s*-+\s*\*+\s*)$/) { s/$2//; } I hope that helps. Hopefully the above might give you some fresh ideas. James -- 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 sort certain pattern from a file
On Jun 16, 2004, at 2:25 PM, Naser Ali wrote: Thanks James, I totally agree with you and appreciate your comments. I was going to refine the whole code by putting in better logic, naming convention, and error handling. I just posted the code baically to share the basic logic of handling the situation. I also did not use the correct wording as you pointed out that $#array is the last index not the size. I ll be more carefull with the wording as well to show my understanding of the matter. I ll definitely be more careful next time. You are right it is good to get in this habbit. Much appreciated your comments and guidance. I meant to do this earlier, but my wife wisked me away on a surprise vacation for my birthday. ;) I'm sure you've about forgot this code by now, but... Just for comparison, I wanted you too see how I might go about writing the script you did (since I just gave general tips last time). The code below should do something similar to what you posted. Maybe it'll give you some ideas. James #!/usr/bin/perl use strict; use warnings; while () { # call with perl script_name input file name print if m/Products/..m/System Totals/; } __END__ -- 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 sort certain pattern from a file
On Jun 16, 2004, at 12:22 PM, Naser Ali wrote: Hello All, Hello. Yesterday I posted a question asking if anyone can suggest a way of accomplishing this. In the mean while I have comeup with a quick and dirty way of processing the data file and sorting it in an array. Once it is sorted, then, I can do whatever however I need to. Code is attached below. If you have any suggestions on better way of accomplishing the same task, please share. Your code is a good start, but there are things that could be better. I'm going to make some general comments below. Then, if you like, you can make some changes and repost and I promise to look again... #!/usr/bin/perl Two lines missing right here: use strict; use warnings; These promise you will obey The Rules of Good Programming and Perl with pay you back with meaningful messages that help you do your job. It's a great deal. Your code won't currently compile with these in. You'll need some changes. Mainly, you need to declare variables before you use them (or when you initialize them). Use my() for this. Example: my $count = 0; $want=1; $count=0; I seriously doubt these are needed and certainly not way up here were they tell me nothing. open(STDIN, test.txt); First, if we ever ask the OS to do work for us, we need to be sure it succeeds. It could fail for many, many reasons and if it does, we want to know why. Second, let STDIN do what STDIN is suppose to do. Use your own file handle. Putting that together, we get: open REPORT, 'test.txt' or die File error: $!; @array=STDIN; An @ called array is redundant and tells me nothing when I'm trying to read code. Use meaningful names. my @lines = REPORT; close (STDIN); close REPORT; print Size of the Array is $#array\n; Wrong. $#array is the last index, not the size. print The array contains , scalar(@array), members\n, The index of the last member is $#array.\n; print @array\n; for ($x=0; $x = $#array; $x++) { print Index[$x] $array[$x]\n; } Yuck. That looks like C. ;) We let are language handle those annoying details for us: for my $i (0..$#array) { print ...; } # or, if you don't need the index... print $_\n for @array; $k=0; Again, meaningful names. What does this variable track, line number? Tell me that. Do we need to track line numbers? No. They're in an array so the line they were on is index + 1. We already have that info. Looks line you are even tracking indexes, not line numbers, so we don't even need the + 1. foreach $line (@array){ chomp $line; if ($line =~ /Product/g) { We don't need a global modifier on our match, we're just checking if it's in there. if (++$count == $want) { Are we just trying to make sure we only get the first one? See my next comment... print line number is --- $k\n; $FIRST=$k; last; # end loop, we'll only get the first one } } $k++; } for my $i (0..$#array) { if ($array[$i] =~ m/Product/) { $FIRST = $i; } elsif ($array[$i] =~ m/System Totals/) { $LAST = $i; } } $i=0; $want=1; $count=0; I doubt we need any of these. See comments above. foreach $line (@array){ chomp $line; if ($line =~ /System Totals/g) { if (++$count == $want) { print line number is --- $i\n; $LAST=$i; } } $i++; } Just like the previous loop. $j=0; for ($ii=$FIRST; $ii = $LAST; $ii++) { $array2[$j] = $array[$ii]; $j++; } What are we doing here? Making another array of first to last? my @first_to_last = @array[$FIRST..$LAST]; for ($y=0; $y = $#array2; $y++) { print Index[$y] $array2[$y]\n; } print FIRST-- $FIRST and LAST---$LAST\n; Let me comment on one last issue. You're slurping the file or reading the whole thing into memory in one move. Then you have to do a dance, to get what you want. Too much hassle. The right way is to only read in what you want and deal with that. You handle this line by line as it's coming in. See if you can setup something like that. Good luck and yell if you need help... James -- 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 open a file for read as well as write
On Jun 15, 2004, at 5:48 AM, Ramprasad A Padmanabhan wrote: I want to open a file using a perl script and change a particular variable in it. I think by setting the $^I variable I can open a file for read and write, But I am not getting any examples anywhere You CAN open a file for read and write, but don't do that here. Open the file for reading and an output file. Copy your original over, making the change you need in passing. Then rename the file the same as the original (warning: Data Loss Step!). Hope that helps. James -- 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 open a file for read as well as write
On Jun 15, 2004, at 10:02 AM, Ramprasad A Padmanabhan wrote: No that is not what I wanted I found that out anyways thanks Want to bet? Guess how the code you posted works, behind the scenes. ;) Seriously, I'm glad you found your answer. James -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Is an Array
On Jun 15, 2004, at 2:24 PM, Angie Ahl wrote: Hi Howdy. Scouring the books to try and find this, but it's evading me. How can I test whether something is an array. For some definition of something that includes references, use ref(). :) ie I have a hash and some values are anon arrays and some are strings. I want to test to see whether one is an array and then traverse it. if ( ref($some_hash{might_be_array_ref}) eq 'ARRAY' ) { # ... } Hope that helps. James -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Elegant quoted word parsing
On Jun 10, 2004, at 9:46 PM, Beau E. Cox wrote: Hi - I am trying to come up with a simple, elegant word parsing script, that: * takes a scalar string, and * splits it into words separating on white space, commas, and a set of delimiters: '' // () {} [] ##, and * returns the array of words. [snip code] There's really not a lot wrong with you're version, save that all that use of substr() and pos() makes me think too much to figure out what it's doing. Here's how I would do the same thing: sub parse_words { my $line = shift; my @words = (); while ( $line =~ s/^\s*(['\/#])(.*?)\1\s*// or $line =~ s/^\s*(\(.*?\)|\{.*?\}|\[.*?\]|.*?)\s*// ) { push @words, $2 || substr $1, 1, length($1) - 2; } push @words, split m/[,\s]+/, $line if length $line; return @words; } I'll leave it to you to decide if that's elegant though. James -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: parsing records
On Jun 10, 2004, at 8:13 AM, Virmani, Amit (GMI Debt Technology) wrote: I am a novice in Perl... I have a file with records of fields in double quotes separated by commas, for example: abc,123xyz,Test 1,Test 2,100,000... What you describe is the CSV file format and there's really no good reason to parse it yourself. The CPAN module Text::CSV_XS is very nice and reduces this problem to practically no work at all. Check it out. James -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Installing the libwww-perl module on Mac os X 10.3.2
On Jun 10, 2004, at 9:39 AM, Phil Calvert wrote: OK, after poking around a bit it seems that the the developer tools need to be installed. Having done that I now get this after running the line perl -MCPAN -e 'CPAN::install LWP' Try: sudo perl -MCPAN -e 'install LWP' You'll need to give the admin password for this. James -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Installing the libwww-perl module on Mac os X 10.3.2
On Jun 10, 2004, at 11:15 AM, Phil Calvert wrote: Hello, Thanks for the reply. When I try that I get; Can't locate object method install via package LWP at -e line 1. I should also say that I tried sudo perl -MCPAN -e 'CPAN::install LWP' and got the result that I reported previously. You might try taking this question to the Mac OS X Perl mailing list. http://lists.perl.org/showlist.cgi?name=macosx This is right up their alley and they're pretty helpful. Sorry I couldn't be more help. James -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Have you seen this error before?
On Jun 10, 2004, at 12:36 PM, jason corbett wrote: I am getting the error: ARRAY(0x1024df4) It's not an error. It's what you see when you try to print an array reference. This line is where it's coming from: print $record\n; If you wanted to see what's in the array referenced by $record, try: print @$record\n; Hope that helps. James -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Have you seen this error before?
On Jun 10, 2004, at 12:56 PM, jason corbett wrote: Thanks for the advice. No problem. What is best for selecting records from a database: Hash or Array? Array if you want to walk it be index, hash if you want to walk it by name. There is no best. ;) James -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Have you seen this error before?
Let's keep our discussions on the list, so we can all help and learn. On Jun 10, 2004, at 1:15 PM, jason corbett wrote: This statement ( print %record}.\n; print %record}.\n; ) from my script below keeps giving the error use of uninitialized value in list argument at filename line ##, STDLIN line 3. How about this? What does this one mean? You did not put a script below for me to examine. Generally, printing a hash should look something like: print $_ = $hash{$_}\n foreach keys %hash; If you instead have a reference to a hash, you need a minor change: print $_ = $hash-{$_}\n foreach keys %$hash; Hope that helps. James -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: regular expression
On Jun 9, 2004, at 6:46 PM, Mandar Rahurkar wrote: Hi, I am looking for URL's that end in .html OR .htm or / $URL =~ m/(?:\.html?|\/)$/ That should do it. James -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: splitting with special characters
On Jun 3, 2004, at 8:11 AM, Singh, Ajit p wrote: Hello All, I am trying to split a string with the / ( forward slash) as the marker. $mystring = abcde/fghi split (///,$mystring) -- gives me compile error split (/\//,$mystring) -- gives me abcdefghi I hope not. The second one is fine: perl -e 'print map { [ $_ ]\n } split /\//, abcde/fghi' [ abcde ] [ fghi ] I suspect something else is going on you're not telling us about. James -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Loading Scalar Vars with Text - Readability
On Jun 1, 2004, at 2:16 PM, PerlDiscuss - Perl Newsgroups and mailing lists wrote: Hi, Adding Perl to the list of languages... and came across a question of loading vars with very long strings... Actually I am modifiying a prior employee's code and want to make it more readable. currently the code is such: my $longlist = Clause1|Clause2|Clause3|Clause4|...|ClauseN; I would like to know why I can't make this more readable? Is it because newline characters would be added to the mix? I would like to do something like this: my $longlist = Clause1| Clause2| Clause3| Clause4| ...| ClauseN; Please copy me directly on your response. T I would use: my $longlist = Clause1| . Clause2| . # ... ClauseN; And yes, the reason you can't put a newline character in the string is because it would take it literally. James -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: I am looking for PERL coder from Romania, Bulgaria, Russia or India
On Jun 1, 2004, at 8:07 PM, Maxipoint Rep Office wrote: I am looking for PERL coder from Romania, Bulgaria, Russia or India for long terms relationship. Then look in the right place. ;) Somewhere like: http://jobs.perl.org/ This is a mailing list where beginners can ask questions and get help with their code. That makes you more than a little off topic. When you do post to a more appropriate place, remember that we spell the language Perl, not PERL. It should score you some points. Good luck with your search. James -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: [Socket Programming]: Need info for Client / Server scenario
On May 30, 2004, at 11:06 PM, [EMAIL PROTECTED] wrote: Hi, Howdy. I need some good links for understanding socket programming (Client / Server programming). Not a link specifically, but I feel I would be letting you down if I didn't mention Network Programming with Perl. That is an excellent book that covers exactly what you're after and much more. I strongly recommend it. I have written some scripts for multiple clients and a server (Forking Server). But I am facing some problems - the server data has to be shared among all the child processes - does this happen when we fork - what should I do for this to happen. There are basically three major approaches to these kinds of servers: Forking, Threaded, and Non-Blocking IO. As others have mentioned, Forking is probably not the way to go in this instance. You want one of the other two. A Threaded server is the easier of the two to write. Unfortunately, it's still plenty involved so I do suggest referencing to book I mentioned above. Another option you might want to look into is POE, which will probably greatly simplify this kind of thing. It have a learning curve you would need to pass too, but can be useful in many applications. Unfortunately, this option isn't covered by the Networking book, so you'll have to use the POE documentation, if you go this way. Good luck. James -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: [Socket Programming]: Need info for Client / Server scenario
On May 31, 2004, at 11:10 AM, [EMAIL PROTECTED] wrote: Hi James, Can you suggest me what this POE is? POE or Perl Object Environment is a multitasking framework. Where can I get info regarding this? http://poe.perl.org/ James -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: regular expression
On May 28, 2004, at 8:31 PM, Mandar Rahurkar wrote: Hi, I am trying to remove from file : 1. all characters but any alphabet and numbers. tr/A-Za-z0-9//cd; # should handle that 2. all trailing spaces should be made to one space. I'm not 100% sure I understand this, but I'm guessing you want: s/ +/ /g; following code doesnt seem to work for objective [1] mentioned above. Can anyone please point out why ? See inline comments below... Thanks, Mandar --- open(fp,$file) or die Cant open $file :$!\n; @cont=fp; [EMAIL PROTECTED]; Is there a reason for this? Code not shown maybe. for(@cont) { tr/A-Z/a-z/; This changes all uppercase letters to their lowercase eqivalents. s/^[a-z0-9]/ /; This replaces one lowercase letter or digit at the beginning of the matched string with a space. s/\s+/ /g; This replaces a run of tabs, spaces and newlines with a single space. } Finally, do you really need to slurp the file? Why not process it line by line? James -- 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 population from system app call
On May 25, 2004, at 12:45 PM, [EMAIL PROTECTED] wrote: All, was hoping anyone could provide some syntax help. I want to populate an array from a system app call like so and then print out each element. my @ftapes = system (evmvol -w label_state=3|grep barcode); print $ftapes[0]; You're looking for backticks: my @ftapes = `evmvol -w label_state=3|grep barcode`; # etc... Hope that helps. James -- 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 population from system app call
On May 25, 2004, at 1:03 PM, [EMAIL PROTECTED] wrote: cool, but why doesn't my @ftapes = system (evmvol -w label_state=3|grep barcode); print $ftapes[0] OR print $ftapes[0,1] work? Because system() does not return the program's output, it returns exit status. I see that it does not support multidimensional arrays, so how do I implement this using system? Multi-dimensional arrays are possible in Perl, with references. If you want to talk about that, please send a new message asking your questions about that topic. You don't do what you show with system() because that's not what it's for. Backticks fill that role. James -- 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 population from system app call
On May 25, 2004, at 1:34 PM, [EMAIL PROTECTED] wrote: ok so now I can get all elements printed using my @ftapes = ( ); my @ftapes = `evmvol -w label_state=3|grep barcode`; foreach $_ (@ftapes) { print $_ , \n; } so now I want to use multidimensional arrays using print $ftapes[0,1] does print $ftapes [0,1] mean print element 0 and element 1 or address 0,1 am I confusing a normal array with a MDarray? Perl arrays are not multidimensional. Using references though, we can get there. Backticks return LINES, not fields. If we want to break them down, we'll need to do that. Can you show a sample output of `evmvol -w label_state`? James -- 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 population from system app call
On May 25, 2004, at 2:24 PM, [EMAIL PROTECTED] wrote: here is the sample output. barcode=E01124 barcode=E01178 barcode=E01195 barcode=E01225 barcode=E01232 maybe I am not understanding when a multidimensional array would be useful? when are these references useful? I really doubt you need a multidimensional array here. The first half of all those lines is the same and since you filtered the output to get just that, I assume we can throw it away. You just want the codes after the = sign, right? Let's ask for that: my @codes = grep s/^barcode=//, `evmvol -w label_state`; Does that get what you're after? James -- 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 population from system app call
On May 25, 2004, at 2:45 PM, [EMAIL PROTECTED] wrote: James, yes it does thanks! Will you be so kind and answer my other question too? Good news. Yes, I will... maybe I am not understanding when a multidimensional array would be useful? when are these references useful? is there a perldoc I can read as well? The docs are: perlreftut and perlref References are great for building complex data structures, ask you guessed. However they add a degree complexity, so make sure you need them before you inflict that upon yourself. James -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: get hash from array
On May 24, 2004, at 7:46 AM, [EMAIL PROTECTED] wrote: sub xpto { my %a = map {$_ = undef} (@_); return \%a; } or sub xpto { return {map {$_ = undef} (@_)}; } I'm using this code but shall exist someting clearner without map. Can you help me? I find map() to be the ideal solution. That's exactly what it's for. You could of course always roll your own loop. What exactly are you trying to fix? James -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: get hash from array
On May 24, 2004, at 8:06 AM, [EMAIL PROTECTED] wrote: I had the idea that something like: sub xpto { my %a; [EMAIL PROTECTED] = (); @[EMAIL PROTECTED] = (); return \%a; } should work. Make the inline change above and it will. James Obviuslly this idea will be used in major subroutines. 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: public/private variables, accessor functions question
On May 20, 2004, at 8:32 AM, Graeme McLaren wrote: Hi, I'm starting to look at OO in PERL, I've written a working class but I don't know how to implement private and public variables and accessor functions, any idea how to do that? Perl takes a very lax view on the whole security issue of objects. From that point of view, the first step is to ask yourself if you really NEED public methods/data? As you say, you have a working class now. What's wrong with it? That view aside, you do have some options. They vary in levels of paranoia and effectiveness. Here's an example of a simple private method: my $private_method = sub { ... }; # and later, a call... $self-$private_method( ... ); As far as data goes, convention is that private Perl instance data starts with an _. There are no rules in place to enforce this, but you could certainly code some, if you really must go that far... Hope that helps. James P.S. Move your package line up, just under the shebang line. P.P.S. Do you know that all objects are using the same query? This could be a feature or a bug, but worth mentioning. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: regex string modification
On May 19, 2004, at 7:21 PM, meb wrote: My regex looks something like this: (Save 1st 20 words): /^(\w|\W){20}/g ^ matches only at the beginning of the string while the /g modifier tries to create a global search matching all occurrences. Matching all of what can only be in one place is pointless. You expression matches 20 word or non-word CHARACTERS, not WORDS. Try something like: s/^((?:\w+\W*?){20}).+$/$1.../ Hope that helps. James -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response