Re: What is the meaning of $normalize->{$1}
Op donderdag 15 juni 2023 22:31:31 CEST schreef Claude Brown: > Is there any prior mention of "$normalise" in the script? Only now I see the first mentioning of $normalize as: $normalize = {} The naming of it is quite confusing to me. More logically would have been "present". Now I understand that it is a test to assure certain lines in the input file should not be present more than once. > Assuming there isn't, most likely "$normalise->{$1}" is building out a > hash-table with "$1" as the key and a value of 1 at each entry. > $normalise will be a reference to that hash. > > To check if this is correct, do this sometime after this code: > > use Data::Dumper; > print Dumper($normalise); Thanks a lot. -- fr.gr. Freek de Kruijf -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: What is the meaning of $normalize->{$1}
Freek de Kruijf writes: > Hi, > > I am trying to understand fully a perl program with the following lines: > >} elsif( /^(\#?\s*(?:pickup|qmgr)\s+)(?:fifo|unix)(\s+.*)/ ) { > if( defined $normalize->{$1} ) { next; } else { $normalize->{$1} = 1; } > I do understand the first line, but I can not find what the second line is > about. $1 contains the content of the first capturing group in the matching regexp. in this case, "#pickup", "#qmgr", "pickup", "qmgr"... etc. $normalize->{$1} means: getting the corresponding value of $1 from the HashRef $normalize. $normalize->{$1} = 1 means: setting the corresponding value of $1 to 1. `next` is a keyword for skipping the rest of loop, so it would seem to me that these 2 lines is inside of a loop. I'm guessing $_ is the iterator of the loop. Assuming that's the case, it appears to me $normalize is used to keep track the occurance of the captured words. Not how may times they occur, just if they occur or not. -- Cheers, Kang-min Liu -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: What is the meaning of $normalize->{$1}
} elsif( /^(\#?\s*(?:pickup|qmgr)\s+)(?:fifo|unix)(\s+.*)/ ) { if( defined $normalize->{$1} ) { next; } else { $normalize->{$1} = 1; } if the string starting at the beginning of the line matches, $1 will contain "zero or one #, zero or more whitespaces, either the word "pickup" or "qmgr", one or more whitespace" - it's then being used as the kev value in the hash referenced by $normalize - if that entry already has a true value (probably a 1) don't do anything, otherwise, assign that key a 1 . Note, to fully match, that string has to be followed by either "fifo" or "unix" and 1 or more whitespaces. Everything (including those last whitespaces) will end up $2. I'm a tad puzzled as to what the purpose could be, there certainly are easier ways to do this. The "use " is including the module .pm in the code, so it's subs/methods etc can be used by the program. On Thu, Jun 15, 2023 at 2:29 PM Freek de Kruijf wrote: > Hi, > > I am trying to understand fully a perl program with the following lines: > >} elsif( /^(\#?\s*(?:pickup|qmgr)\s+)(?:fifo|unix)(\s+.*)/ ) { > if( defined $normalize->{$1} ) { next; } else { $normalize->{$1} = > 1; } > I do understand the first line, but I can not find what the second line is > about. > > As far as can see the tested line in $_, from a file, is all ASCII with > lower > case characters. At the begin of the perl program the is no "use > ". > > -- > > fr.gr. > > Freek de Kruijf > > > > > -- > To unsubscribe, e-mail: beginners-unsubscr...@perl.org > For additional commands, e-mail: beginners-h...@perl.org > http://learn.perl.org/ > > > -- a Andy Bach, afb...@gmail.com 608 658-1890 cell 608 261-5738 wk
What is the meaning of $normalize->{$1}
Hi, I am trying to understand fully a perl program with the following lines: } elsif( /^(\#?\s*(?:pickup|qmgr)\s+)(?:fifo|unix)(\s+.*)/ ) { if( defined $normalize->{$1} ) { next; } else { $normalize->{$1} = 1; } I do understand the first line, but I can not find what the second line is about. As far as can see the tested line in $_, from a file, is all ASCII with lower case characters. At the begin of the perl program the is no "use ". -- fr.gr. Freek de Kruijf -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
What Happened to Net::DNS and a few others on December 1?
We run some FreeBSD systems using FreeBSD9.1 and 9.3 and the response to perl -version is: This is perl 5, version 18, subversion 4 (v5.18.4) built for amd64-freebsd-thread-multi On December 1 of 2014, we were alerted to the fact that some perl scripts were no longer working. The complaint was about Net::DNS on one system and Warnings::Unused on another system and expect.pm on yet another system. I used cpanp -i to install all the needed modules with no trouble at all and all the scripts came back to life. I am not complaining at all but curious as to what mechanism caused older modules to basically expire and need to be replaced. Thank you. Martin McCormick -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: What Happened to Net::DNS and a few others on December 1?
Hi Martin, On Tue, 02 Dec 2014 11:45:58 -0600 Martin G. McCormick mar...@server1.shellworld.net wrote: We run some FreeBSD systems using FreeBSD9.1 and 9.3 and the response to perl -version is: This is perl 5, version 18, subversion 4 (v5.18.4) built for amd64-freebsd-thread-multi On December 1 of 2014, we were alerted to the fact that some perl scripts were no longer working. The complaint was about Net::DNS on one system and Warnings::Unused on another system and expect.pm on yet another system. I used cpanp -i to install all the needed modules with no trouble at all and all the scripts came back to life. I am not complaining at all but curious as to what mechanism caused older modules to basically expire and need to be replaced. There could be several reasons: 1. The @INC of the installed module was perl-version-specific. E.g in my perl -V: /usr/lib/perl5/site_perl/5.20.1 /usr/lib/perl5/site_perl/5.20.1/x86_64-linux-thread-multi /usr/lib/perl5/site_perl/5.20.0 /usr/lib/perl5/site_perl/5.20.0/x86_64-linux-thread-multi /usr/lib/perl5/site_perl/5.18.2 /usr/lib/perl5/site_perl/5.18.1 /usr/lib/perl5/site_perl/5.18.0 /usr/lib/perl5/site_perl/5.16.3 /usr/lib/perl5/site_perl/5.16.3 /usr/lib/perl5/site_perl/5.16.2 /usr/lib/perl5/site_perl/5.16.2 /usr/lib/perl5/site_perl/5.16.1 /usr/lib/perl5/site_perl/5.16.1 /usr/lib/perl5/site_perl /usr/lib/perl5/vendor_perl/5.20.1 /usr/lib/perl5/vendor_perl/5.20.1/x86_64-linux-thread-multi /usr/lib/perl5/vendor_perl/5.20.0 /usr/lib/perl5/vendor_perl/5.20.0/x86_64-linux-thread-multi /usr/lib/perl5/vendor_perl/5.18.2 /usr/lib/perl5/vendor_perl/5.18.1 /usr/lib/perl5/vendor_perl/5.18.0 /usr/lib/perl5/vendor_perl/5.16.3 /usr/lib/perl5/vendor_perl/5.16.3 /usr/lib/perl5/vendor_perl/5.16.2 /usr/lib/perl5/vendor_perl/5.16.2 /usr/lib/perl5/vendor_perl/5.16.1 /usr/lib/perl5/vendor_perl/5.16.1 /usr/lib/perl5/vendor_perl/5.16.0 /usr/lib/perl5/vendor_perl/5.16.0 As you can see, some of them are versioned and if the previous versions are not added to the inc of the new perl, the modules installed there won't be available. 2. Sometimes new versions of perl-5.x break the XS API or ABI and can no longer load the shared libraries that are associated with some binary-including modules. 3. Possible other reasons. Regards, Shlomi Fish Thank you. Martin McCormick -- - Shlomi Fish http://www.shlomifish.org/ Stop Using MSIE - http://www.shlomifish.org/no-ie/ God gave us two eyes and ten fingers so we will type five times as much as we read. Please reply to list if it's a mailing list post - http://shlom.in/reply . -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: What Happened to Net::DNS and a few others on December 1?
Shlomi Fish writes: There could be several reasons: 1. The @INC of the installed module was perl-version-specific. E.g in my perl -V: As you can see, some of them are versioned and if the previous versions are not added to the inc of the new perl, the modules installed there won't be available. 2. Sometimes new versions of perl-5.x break the XS API or ABI and can no longer load the shared libraries that are associated with some binary-including modules. 3. Possible other reasons. Thanks very much. I suspect your second reason was what happened here. Martin -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
perlre(1) and substitution evaluations
perlre(1) seems to be missing information about substitution evaluations with the /e option. The functionality is present in perl: perl -e '$_=2; s/2/1+3/e; print' But it is not listed in the pod documentation for v5.16.3 or v5.18.1. The modifier /e is described in Programming Perl, 4th ed, pp 186, 254-255. Where should suggestions for corrections be sent? Could something like the text below be added? Regards, /Lars $ diff perlre.pod perlre.pod.orig 108,113d107 =item e X/e Treat the replacement portion as an interpreted expression. Each additional C/e modifier after the first functions as an eval() around the code to execute. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: perlre(1) and substitution evaluations
Lars Noodén lars.noo...@gmail.com wrote: perlre(1) seems to be missing information about substitution evaluations with the /e option. The functionality is present in perl: perl -e '$_=2; s/2/1+3/e; print' But it is not listed in the pod documentation for v5.16.3 or v5.18.1. The modifier /e is described in Programming Perl, 4th ed, pp 186, 254-255. Where should suggestions for corrections be sent? Could something like the text below be added? Regards, /Lars $ diff perlre.pod perlre.pod.orig 108,113d107 =item e X/e Treat the replacement portion as an interpreted expression. Each additional C/e modifier after the first functions as an eval() around the code to execute. The substituted string isn't a regular expression. The substitute operator s/// is described in `perlop`. Rob -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: perlre(1) and substitution evaluations
On 11/30/2013 4:07 AM, Lars Noodén wrote: perlre(1) seems to be missing information about substitution evaluations with the /e option. The functionality is present in perl: perl -e '$_=2; s/2/1+3/e; print' But it is not listed in the pod documentation for v5.16.3 or v5.18.1. The modifier /e is described in Programming Perl, 4th ed, pp 186, 254-255. Where should suggestions for corrections be sent? Could something like the text below be added? Regards, /Lars $ diff perlre.pod perlre.pod.orig 108,113d107 =item e X/e Treat the replacement portion as an interpreted expression. Each additional C/e modifier after the first functions as an eval() around the code to execute. See the substitution operator in perlop: |||http://perldoc.perl.org/functions/s.html| A |/e| will cause the replacement portion to be treated as a full-fledged Perl expression and evaluated right then and there. It is, however, syntax checked at compile-time. A second |e| modifier will cause the replacement portion to be |eval http://perldoc.perl.org/functions/eval.html|ed before being run as a Perl expression. ... Here's the cross ref. in perlre: For reference on how regular expressions are used in matchings of m//, operations, plus various examples of the same, see discussions of m//, s///, qr// and ?? in Regexp Quote-Like Operators in perlop.ls of Modifiers quoted constructs in perlop -- Charles DeRykus -- Charles DeRykus
Re: perlre(1) and substitution evaluations
On 11/30/2013 02:55 PM, Charles DeRykus wrote: See the substitution operator in perlop: |||http://perldoc.perl.org/functions/s.html| A |/e| will cause the replacement portion to be treated as a full-fledged Perl expression and evaluated right then and there. It is, however, syntax checked at compile-time. A second |e| modifier will cause the replacement portion to be |eval http://perldoc.perl.org/functions/eval.html|ed before being run as a Perl expression. ... Here's the cross ref. in perlre: For reference on how regular expressions are used in matchings of m//, operations, plus various examples of the same, see discussions of m//, s///, qr// and ?? in Regexp Quote-Like Operators in perlop.ls of Modifiers quoted constructs in perlop Thanks. I see those in perlop and perlfunc. In perlfunc, it is grouped as Regular expressions and pattern matching though that man page just points to perlop. A really clear description in perlre would help, since the other modifiers are already there and they belong all together. The two s/// modifiers, /e and /r, should be at least named in that group at least as one-line summaries. Regards, /Lars -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: perlre(1) and substitution evaluations
On 11/30/2013 5:16 AM, Lars Noodén wrote: On 11/30/2013 02:55 PM, Charles DeRykus wrote: [ .. Thanks. I see those in perlop and perlfunc. In perlfunc, it is grouped as Regular expressions and pattern matching though that man page just points to perlop. A really clear description in perlre would help, since the other modifiers are already there and they belong all together. The two s/// modifiers, /e and /r, should be at least named in that group at least as one-line summaries. Yes. IMO it should be much easier to find the doc ref's for /e and even /r too. I seem to recall strong advocacy in the past for adding this or similar pointers. Long overdue :) -- Charles DeRykus -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Intermediate Perl - Chapter 7 Exercise 1 Question
I am working my way through Intermediate Perl and have a question concerning one of the exercises (It's a long-ish exercise, so I won't bother typing it out as it's irrelevant to the question at hand). The author's solution contains the following code: ... code ... my ($gather, $yield) = gather_mtime_between($start, $stop); find($gather, @starting_directories); my @files = yield-(); ... more code ... sub gather_mtime_between{ my ($begin, $end) = @_; my @files; my $gatherer = sub { *my $timestamp (stat $_)[9]* unless (defined $timestamp) { warn ...; return; } ... }; ... } My question is about the bold: Where is $_ getting its value? Richard Johnson
Re: Intermediate Perl - Chapter 7 Exercise 1 Question
On 12/10/2012 04:39 PM, Rich Johnson wrote: I am working my way through Intermediate Perl and have a question concerning one of the exercises (It's a long-ish exercise, so I won't bother typing it out as it's irrelevant to the question at hand). The author's solution contains the following code: ... code ... my ($gather, $yield) = gather_mtime_between($start, $stop); find($gather, @starting_directories); my @files = yield-(); ... more code ... sub gather_mtime_between{ my ($begin, $end) = @_; my @files; my $gatherer = sub { *my $timestamp (stat $_)[9]* unless (defined $timestamp) { warn ...; return; } ... }; ... } My question is about the bold: Where is $_ getting its value? first off, did you type that code in by hand? there is no = in the line you marked with **. you need to read the docs on the File::Find module. it does a callback to a sub (in this case the code ref assigned to $gather from gather_mtime_between). before it does each callback find() sets $_ to the file it just found. there are other things set globally by find which can be very useful so learn more about that module. uri -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
My Long Script (1)
#!/usr/local/bin/perl # use warnings; # use strict; # use diagnostics; use CGI; my $cgi = new CGI; my ( $topic, $score, $lastnum, $answer, $anum, $bnum, $cnum, $dnum, $enum,$smarts, $playlevel, $c_topic, $c_smarts, $c_playlevel, $c_score, $c_lastnum, $c_goodans, $stimulus, $texta, $textb, $textc, $textd, $texte,$defnum, $smiley, $feedback, $goodans, $restart, @data,@cat, @term, @def, @story,@candidate, @termnum, $sound ); my $instructions = (Click the button next to the best response); my $ops = 0; # GET COOKIES $topic = $cgi-cookie('topic'); $smarts= $cgi-cookie('smarts'); $playlevel = $cgi-cookie('playlevel'); $score = $cgi-cookie('score'); $lastnum = $cgi-cookie('lastnum'); $goodans = $cgi-cookie('goodans'); # IF NEW CATEGORY THEN (RE)START TUTORIAL, ELSE GET USER ANSWER if ( $cgi-param('Category') ) { $restart = 1; $topic = $cgi-param('Category'); $smarts= 0; $playlevel = 0; $score = 0; $lastnum = 0; } elsif ( $cgi-param('Answer') ) { $answer = $cgi-param('Answer'); } elsif ( $cgi-param('Next') ) { $restart = 1; } if ($topic) {# RUN TUTORIAL if ( $answer and ( $playlevel 3 ) ) { # SUBSTITUTE SPACE FOR '+' IN $answer $_ = $answer; s/\+/ /g; $answer = $_; # RTRIM $answer AND MAKE SURE IT'S ALL LOWER CASE $answer =~ s/\s+$//; $answer = lc($answer); # FIX FRENCH CHARACTERS if( $answer eq deja entendu ) { $answer = déjà entendu; } elsif ( $answer eq deja vu ) { $answer = déjà vu; } elsif ( $answer eq deja vecu ){ $answer = déjà vécu; } elsif ( $answer eq folie a deux ) { $answer = folie à deux; } elsif ( $answer eq jamais vecu ) { $answer = jamais vécu; } elsif ( $answer eq d%e9j%e0 entendu ) { $answer = déjà entendu; } elsif ( $answer eq d%e9j%e0 vu ) { $answer = déjà vu; } elsif ( $answer eq d%e9j%e0 v%e9cu ) { $answer = déjà vécu; } elsif ( $answer eq folie %e0 deux ) { $answer = folie à deux; } elsif ( $answer eq jamais v%e9cu ){ $answer = jamais vécu; } }# END PLAYLEVEL 4 # LOAD DATA open FH, /home1/theinfp0/public_html/psychdef/tutorial.fil or die $!; while (FH) { if ( $topic eq REVIEW ) { $termnum[ $ops++ ] = $_; } elsif (/$topic/) { $termnum[ $ops++ ] = $_; } } close FH; $defnum = $ops;# NUMBER OF TERMS IN DATA SET # PARSE $_ TO GET $term(32) $cat(16) $def(64) $story(128) via @data: $ops = 0; foreach (@termnum) { @data = /(.{16})/g; $cat[$ops] = $data[0]; $term[$ops] = $data[1] . $data[2]; $def[$ops] = $data[3] . $data[4] . $data[5] . $data[6]; $story[$ops] = $data[7] . $data[8] . $data[9] . $data[10] . $data[11] . $data[12] . $data[13] . $data[14]; # RIGHT TRIM STRINGS $cat[$ops] =~ s/\s+$//; $term[$ops] =~ s/\s+$//; $def[$ops] =~ s/\s+$//; $story[ $ops++ ] =~ s/\s+$//; } # EVALUATE RESPONSE AND PROVIDE FEEDBACK, ADJUSTING SCORES if ( $answer and ( $answer ne $goodans ) ) { $answer = 0; } if ($answer) { $smarts++; $score= ++$score + $playlevel; $smiley = 1; # SUCCESS $feedback = You got it right!; } else { $smarts-- unless $restart; $feedback = Better study this!; } if( $smarts -4 ) { $playlevel--; $smarts = 0; } elsif ( $smarts 4 ) { $playlevel++; $smarts = 0; } # NEXT QUESTION if ( $answer or $restart ) {# AVOID CHANGING $lastnum FOR WRONG ANSWER if ( $playlevel 1 ) { while (1) { $termnum[0] = int( rand($defnum) ); last unless ( $termnum[0] == $lastnum ); } $lastnum = $termnum[0]; $stimulus = $term[ $termnum[0] ]; $candidate[0] = $def[ $termnum[0] ]; while (1) { $termnum[1] = int( rand($defnum) ); last unless ( $termnum[1] == $termnum[0] ); } $candidate[1] = $def[ $termnum[1] ]; $anum = int( rand(2) ); $bnum = abs( $anum - 1 ); $texta= $candidate[$anum]; $textb= $candidate[$bnum]; if ( $texta eq $candidate[0] ) { $goodans = A; } else { $goodans = B; } } elsif ( $playlevel == 1 ) { while (1) { $termnum[0] = int( rand($defnum) ); last unless ( $termnum[0] == $lastnum ); } $lastnum = $termnum[0
strict subs in use at -e line 1.
$ perl -Mstrict -wle '{my $char = chr(Ox394) ; print $char;}' Bareword Ox394 not allowed while strict subs in use at -e line 1. Execution of -e aborted due to compilation errors. I don't understand the above error message well, Thanks ahead for any explainations, Best Regards, -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: strict subs in use at -e line 1.
On Tue, Mar 06, 2012 at 11:31:59PM +0800, lina wrote: $ perl -Mstrict -wle '{my $char = chr(Ox394) ; print $char;}' Bareword Ox394 not allowed while strict subs in use at -e line 1. Execution of -e aborted due to compilation errors. I don't understand the above error message well, The immediate problem you are seeing is that you should be using the number zero (0) rather than the uppercase letter O (O). If you are not using a font which allows you to easily distinguish between then two, may I suggest inconsolata as a good choice for programming? -- Paul Johnson - p...@pjcj.net http://www.pjcj.net -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: strict subs in use at -e line 1.
On 12-03-06 10:31 AM, lina wrote: $ perl -Mstrict -wle '{my $char = chr(Ox394) ; print $char;}' Bareword Ox394 not allowed while strict subs in use at -e line 1. Execution of -e aborted due to compilation errors. I don't understand the above error message well, Thanks ahead for any explainations, Best Regards, First time I tried it, I got the same error. But after goofing around a bit, it started to work. $ perl -Mstrict -wle '{my $char = chr(Ox394) ; print $char;}' Bareword Ox394 not allowed while strict subs in use at -e line 1. Execution of -e aborted due to compilation errors. $ perl -Mstrict -wle '{my $char = chr(Ox94) ; print $char;}' Bareword Ox94 not allowed while strict subs in use at -e line 1. Execution of -e aborted due to compilation errors. $ perl -Mstrict -wle '{my $char = chr(Ox4) ; print $char;}' Bareword Ox4 not allowed while strict subs in use at -e line 1. Execution of -e aborted due to compilation errors. $ perl -Mstrict -wle '{my $char = chr(394) ; print $char;}' Wide character in print at -e line 1. Ɗ $ perl -Mstrict -wle '{my $char = chr(0394) ; print $char;}' Illegal octal digit '9' at -e line 1, at end of line Execution of -e aborted due to compilation errors. $ perl -Mstrict -wle '{my $char = chr(034) ; print $char;}' $ perl -Mstrict -wle '{my $char = chr(044) ; print $char;}' $ $ perl -e'print 0x34' 52$ perl -e'print chr(0x34)' 4$ perl -e'$char=chr(0x34)' $ perl -e'$char=chr(0x34);print $char' 4$ perl -e'my$char=chr(0x34);print $char' 4$ perl Mstrict -wle '{my $char = chr(0x30) ; print $char;}' 0 $ perl -Mstrict -wle '{my $char = chr(0x394) ; print $char;}' Wide character in print at -e line 1. Δ $ -- Just my 0.0002 million dollars worth, Shawn Programming is as much about organization and communication as it is about coding. It's Mutual Aid, not fierce competition, that's the dominate force of evolution. Of course, anyone who has worked in open source already knows this. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: strict subs in use at -e line 1.
On Tue, Mar 6, 2012 at 9:31 AM, lina lina.lastn...@gmail.com wrote: $ perl -Mstrict -wle '{my $char = chr(Ox394) ; print $char;}' Bareword Ox394 not allowed while strict subs in use at -e line 1. Execution of -e aborted due to compilation errors. I don't understand the above error message well, Thanks ahead for any explainations, Best Regards, -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/ If you are simply trying to assign chr(0x394) to varible $char and then print $char then the below will work. perl -Mstrict -wle '{my $char = chr(0x394) ; print $char;}' HTH, Chris -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: strict subs in use at -e line 1.
On Tue, Mar 6, 2012 at 11:42 PM, Paul Johnson p...@pjcj.net wrote: On Tue, Mar 06, 2012 at 11:31:59PM +0800, lina wrote: $ perl -Mstrict -wle '{my $char = chr(Ox394) ; print $char;}' Bareword Ox394 not allowed while strict subs in use at -e line 1. Execution of -e aborted due to compilation errors. I don't understand the above error message well, The immediate problem you are seeing is that you should be using the number zero (0) rather than the uppercase letter O (O). Thanks, I have never tried the hexadecimal output before. I thought ... why is 0, not O? If you are not using a font which allows you to easily distinguish between then two, may I suggest inconsolata as a good choice for I can easily tell the two, I just read from pdf and took it as O, just googled the inconsolata, I will stick to the gvim Thanks again, programming? -- Paul Johnson - p...@pjcj.net http://www.pjcj.net -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Can't use string (1) as a HASH ref while strict refs
Rob == Rob Dixon rob.di...@gmx.com writes: Rob Randal, as I opened, I had started to enjoy and respect your posts here Rob and elsewhere. You were never required to reply to my 'ignorant post', Rob yet you chose to show your foolish emptiness once again. But I am highly motivated to reduce and contain the damage caused by misinformation. You were spreading misinformation to others. If my reply to you had no impact on you, that is sad, but at least the others reading this thread will be more enlightened. -- Randal L. Schwartz - Stonehenge Consulting Services, Inc. - +1 503 777 0095 mer...@stonehenge.com URL:http://www.stonehenge.com/merlyn/ Smalltalk/Perl/Unix consulting, Technical writing, Comedy, etc. etc. See http://methodsandmessages.posterous.com/ for Smalltalk discussion -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Can't use string (1) as a HASH ref while strict refs
On 27/09/2011 17:35, Randal L. Schwartz wrote: Rob == Rob Dixonrob.di...@gmx.com writes: Rob Randal, as I opened, I had started to enjoy and respect your posts here Rob and elsewhere. You were never required to reply to my 'ignorant post', Rob yet you chose to show your foolish emptiness once again. But I am highly motivated to reduce and contain the damage caused by misinformation. You were spreading misinformation to others. If my reply to you had no impact on you, that is sad, but at least the others reading this thread will be more enlightened. If you think you are doing the community a favour by making it a threatening place place where people can expect their ideas to be met with sardonic derision then all I can do is ask you to think again. I doubt if I can say anything more to change your mind. Rob -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Can't use string (1) as a HASH ref while strict refs
On 21/09/2011 20:57, Randal L. Schwartz wrote: Rob == Rob Dixonrob.di...@gmx.com writes: Rob I don't have Try::Tiny installed, but will take a look. I am back at my desk, and have this horror from you to respond to. I had started to enjoy some of your posts, and hoped that your legendary brutal negativity was beginning to lapse. Whatever your thoughts, please drop the shield that says you are responding to people's coding rather than the people themselves. The difference is an age-old philosophy, and I would love to hear your thoughts on the distinction. I have an addressbar query shortcut of: http://search.cpan.org/perldoc/#query# aliased to perldoc, so I can type perldoc Try::Tiny and get the latest manpage on it directly from the CPAN without installing it. Hooray for you. I use my editor as an IDE to do the very same thing. Rob If you mean that $@ may be accessed by several pieces of code Rob when a program dies, No. See the referenced docs. I have thought a lot about how an 'eval' block may be unsafe, and have commented several times to discourage it. I have now read the POD for Try::Tiny, and I cannot see anything that I hadn't already envisaged: that when a Perl process dies $@ may be accessed by several pieces of code. The Try::Tiny documentation says this When you run an eval block and it succeeds, $@ will be cleared, potentially clobbering an error that is currently being caught. Oddly, you chose to misquote me by splitting a sentence. Your version of my post is irregular and inappropriate. It is not what I would have written. What I wrote was I don't have Try::Tiny installed, but will take a look. If you mean that $@ may be accessed by several pieces of code when a program dies, then I agree, but my main concern is that try / catch are both simply prototyped subroutines, and the compile can not tie things down to requiring try BLOCK catch BLOCK; Your version: Rob then I agree, but my main concern is that try / catch are both Rob simply prototyped subroutines, and the compile can not tie things Rob down to requiring Rob Robtry BLOCK catch BLOCK; Why does that matter? It's the semantics that you have to get right, not just the syntax. I am sure you know the answer to that. It matters because the presentation of the mechanism is deceptive. It looks very like while () { : } continue : } but instead is something very different. As I have described, it amounts to two obscure prototyped subroutine definitions. From the source: sub try (;@); and sub catch (;@); which is far from what the average man expects of 'while', 'for', 'continue' and so on. It is a deception, and should not be published until the equivalent functionality is part of the Perl language. Rob Maybe Try::Tiny works differently but I can't see how it could Rob cover this. Again, read the referenced doc. It would have taken you about 5 minutes, and you wouldn't have had to write this entire ignorant reply or waste my time replying to it. Randal, as I opened, I had started to enjoy and respect your posts here and elsewhere. You were never required to reply to my 'ignorant post', yet you chose to show your foolish emptiness once again. It seems to me that you place your entire worth in your extreme and detailed knowledge of Perl and its teaching. Please believe me that, as a fellow human being, I would love to hear about your personal experiences and how programming has played a part in your character. You certainly seem insecure, and your silliness about your criticism not applying to a person but to their deeds needs to be washed ashore. Stop it and be real. Believe me, you wouldn't cease to exist if you lost your technical ability. Rob -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Can't use string (1) as a HASH ref while strict refs
On 20/09/2011 15:57, Randal L. Schwartz wrote: Rob == Rob Dixonrob.di...@gmx.com writes: Rob For me, the bottom line is that try / catch is a funky showpiece that Rob pushes Perl syntax beyond its limits. No one who sees your code will Rob thank you for using it, and you should remove it in preference of a Rob simple check on $@. Completely disagree. Checking $@ *appears* to be easy, but is prone to error. Try::Tiny is best of breed to fix this. I would prefer people use Try::Tiny instead of trying to handcraft the $@ checking and getting it wrong. For example, if you don't know what's wrong with this: eval { ... }; if ($@) { ... } then you *need* to start using Try::Tiny. See especially the section beginning BACKGROUND on the Try::Tiny manpage. I don't have Try::Tiny installed, but will take a look. If you mean that $@ may be accessed by several pieces of code when a program dies, then I agree, but my main concern is that try / catch are both simply prototyped subroutines, and the compile can not tie things down to requiring try BLOCK catch BLOCK; Maybe Try::Tiny works differently but I can't see how it could cover this. Rob -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Can't use string (1) as a HASH ref while strict refs
Rob == Rob Dixon rob.di...@gmx.com writes: Rob I don't have Try::Tiny installed, but will take a look. I have an addressbar query shortcut of: http://search.cpan.org/perldoc/#query# aliased to perldoc, so I can type perldoc Try::Tiny and get the latest manpage on it directly from the CPAN without installing it. Rob If you mean that Rob $@ may be accessed by several pieces of code when a program dies, No. See the referenced docs. Rob then I agree, but my main concern is that try / catch are both Rob simply prototyped subroutines, and the compile can not tie things Rob down to requiring Rob try BLOCK catch BLOCK; Why does that matter? It's the semantics that you have to get right, not just the syntax. Rob Maybe Try::Tiny works differently but I can't see how it could Rob cover this. Again, read the referenced doc. It would have taken you about 5 minutes, and you wouldn't have had to write this entire ignorant reply or waste my time replying to it. :( -- Randal L. Schwartz - Stonehenge Consulting Services, Inc. - +1 503 777 0095 mer...@stonehenge.com URL:http://www.stonehenge.com/merlyn/ Smalltalk/Perl/Unix consulting, Technical writing, Comedy, etc. etc. See http://methodsandmessages.posterous.com/ for Smalltalk discussion -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Can't use string (1) as a HASH ref while strict refs
Rob == Rob Dixon rob.di...@gmx.com writes: Rob For me, the bottom line is that try / catch is a funky showpiece that Rob pushes Perl syntax beyond its limits. No one who sees your code will Rob thank you for using it, and you should remove it in preference of a Rob simple check on $@. Completely disagree. Checking $@ *appears* to be easy, but is prone to error. Try::Tiny is best of breed to fix this. I would prefer people use Try::Tiny instead of trying to handcraft the $@ checking and getting it wrong. For example, if you don't know what's wrong with this: eval { ... }; if ($@) { ... } then you *need* to start using Try::Tiny. See especially the section beginning BACKGROUND on the Try::Tiny manpage. -- Randal L. Schwartz - Stonehenge Consulting Services, Inc. - +1 503 777 0095 mer...@stonehenge.com URL:http://www.stonehenge.com/merlyn/ Smalltalk/Perl/Unix consulting, Technical writing, Comedy, etc. etc. See http://methodsandmessages.posterous.com/ for Smalltalk discussion -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Can't use string (1) as a HASH ref while strict refs
Hi, I was getting this error message for one of my script. The reason came out out to be, I had not place a semi-colon at the end of try-catch block. try { something } catch some_exception { do something } After I placed the semi-colon, I am no longer getting this error (Can't use string (1) as a HASH ref while strict refs) try { something } catch some_exception { do something }; My questions is I have quite a few scripts that are using the SAME try-catch block without a semi-colon but those are working seamlessly. They why was I getting the error for only this try-catch block. Is there some rule which we need to follow while using try-catch in Perl? Thanks, Parag
Re: Can't use string (1) as a HASH ref while strict refs
On 9/19/11 Mon Sep 19, 2011 5:11 PM, Parag Kalra paragka...@gmail.com scribbled: Hi, I was getting this error message for one of my script. The reason came out out to be, I had not place a semi-colon at the end of try-catch block. try { something } catch some_exception { do something } After I placed the semi-colon, I am no longer getting this error (Can't use string (1) as a HASH ref while strict refs) try { something } catch some_exception { do something }; My questions is I have quite a few scripts that are using the SAME try-catch block without a semi-colon but those are working seamlessly. They why was I getting the error for only this try-catch block. Is there some rule which we need to follow while using try-catch in Perl? Yes: always end your try-catch statement with a semicolon! :) The try-catch mechanism is not part of the Perl language (not as of Perl 5.10, anyway). There are modules that provide try-catch via prototyped functions try($) and catch() that take code blocks as their first argument. These include Error.pm, TryCatch.pm, Try::Tiny.pm, Exception.pm, and Fatal.pm (according to http://en.wikipedia.org/wiki/Exception_handling_syntax#Perl). Since these are functions and not language keywords, they require a semicolon at the end so that the subsequent statements are not interpreted as additional catch() {} blocks. Are you using one of these modules? The result of leaving off the semicolon probably depends upon what follows after the last catch block. While most of your programs do not issue that same error message, it is still likely that they are not doing what you want them to do. If you want further help, please post a complete, short program that demonstrates your problem. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Can't use string (1) as a HASH ref while strict refs
On 20/09/2011 01:11, Parag Kalra wrote: I was getting this error message for one of my script. The reason came out out to be, I had not place a semi-colon at the end of try-catch block. try { something } catch some_exception { do something } After I placed the semi-colon, I am no longer getting this error (Can't use string (1) as a HASH ref while strict refs) try { something } catch some_exception { do something }; My questions is I have quite a few scripts that are using the SAME try-catch block without a semi-colon but those are working seamlessly. They why was I getting the error for only this try-catch block. Is there some rule which we need to follow while using try-catch in Perl? Hi Parag The first problem I see is that you are passing 'catch' the return value of the subroutine 'some_exception' when it expects a code block. The correct syntax is try { some code that may cause an exception } catch { handle exception passed in $_ } The way try / catch works is obscure, and presented in Programming Perl as an example of how subroutine prototypes could be useful, but the declaration of try looks like sub try ($); so to express its functionality your code should be formatted like this try ( { some code that may cause an exception }, catch ({ handle exception passed in $_ }) ); which clearly requires a semicolon after the closing parenthesis. For me, the bottom line is that try / catch is a funky showpiece that pushes Perl syntax beyond its limits. No one who sees your code will thank you for using it, and you should remove it in preference of a simple check on $@. It cannot be a good sign if you don't understand where the semicolons should go! HTH, Rob -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: File::path the option keep_root = 1 does not seem to work
On 19/04/2011 10:42, Agnello George wrote: File::path the option keep_root = 1 does not seem to work for me use File::Path; rmtree( '/temp/auto', { verbose =1 , keep_root = 1}); it throw me the output unlink /temp/auto/test6 unlink /temp/auto/test5 unlink /temp/auto/test4 rmdir /temp/auto the option keep_root = 1 should keep the root path ?? You are right. I can't fault the code you have posted. There must be something else wrong. Please show us the entire program? Rob -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
File::path the option keep_root = 1 does not seem to work
hi File::path the option keep_root = 1 does not seem to work for me use File::Path; rmtree( '/temp/auto', { verbose =1 , keep_root = 1}); it throw me the output unlink /temp/auto/test6 unlink /temp/auto/test5 unlink /temp/auto/test4 rmdir /temp/auto the option keep_root = 1 should keep the root path ?? -- Regards Agnello D'souza
Re: Behavior of minimal when applied to - {1,}? ot to - {0,}?
Rob Dixon wrote in message news:4d48bdc7.6050...@gmx.com... On 01/02/2011 02:30, Chris Charley wrote: #!/usr/bin/perl use strict; use warnings; $_ = [][12/21/10 18:39:22] [oasetup] [oasetup] [INFO] Installing the HPOvXpl package...; for my $re (qw{ ^\[(.+?)\] ^\[(.*?)\] }) { my ($dt) = /$re/ or die Horrible death\n;; print $re, ' ', '$dt', \n; } __END__ C:\Old_Data\perlpperl t5.pl ^\[(.+?)\] '][12/21/10 18:39:22' ^\[(.*?)\] '' C:\Old_Data\perlp My question in the code above is the '.+?' behavior. I had guessed that it would attempt to match the empty brackets and fail, (because it requires 1 or more characters). Instead, it captures the right bracket and the left opening bracket and contents (date) of the second bracket pair. Does the regex first consume a character before checking the next character to see if it is the first one *after* the expression the '+?' is applied to. It seems to be the way this regex behaved. Or does the regex see its going to fail with the empty first bracket pair, and so tries to advance to somehow find a match? This seems pretty vague. I thought a regex first looks for the next character beyond the expression the '+?' is applied to, before it consumes any characters? That is the way the second regex, '.*?', behaved. Hope it was clear enough. :-) Hey Chris /.+?/ requires at least one character, so /^\[.+?\]/ will need at least three characters for a match. The engine will try to match /^\[.\]/ and fail, then /^\[..\]/, then /^\[...\]/ and so on. Perl doesn't care that the object string's second character is a ']' - all it has to do is match /./ and that will do fine. This process continues until the pattern is long enough to reach the first closing square bracket it sees, and so comsumes the date/time field to get there. /.*?/ will match zero characters, so the initial [] fits the bill immediately. The ? doesn't change the lower bound of the character count - it simply says to match as few as possible. /.{2,4}/ will match four characters, while /.{2,4}?/ will match two. HTH, Rob Hi Rob, Thanks for the good answers from you and Uri. Yes, fulfilling the min of a quantifier before applying the lazy behavior of the ? is what had me stumped. The ? doesn't change the lower bound and I was hazy in my mind about that. Chris -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Behavior of minimal when applied to - {1,}? ot to - {0,}?
#!/usr/bin/perl use strict; use warnings; $_ = [][12/21/10 18:39:22] [oasetup] [oasetup] [INFO] Installing the HPOvXpl package...; for my $re (qw{ ^\[(.+?)\] ^\[(.*?)\] }) { my ($dt) = /$re/ or die Horrible death\n;; print $re, ' ', '$dt', \n; } __END__ C:\Old_Data\perlpperl t5.pl ^\[(.+?)\] '][12/21/10 18:39:22' ^\[(.*?)\] '' C:\Old_Data\perlp My question in the code above is the '.+?' behavior. I had guessed that it would attempt to match the empty brackets and fail, (because it requires 1 or more characters). Instead, it captures the right bracket and the left opening bracket and contents (date) of the second bracket pair. Does the regex first consume a character before checking the next character to see if it is the first one *after* the expression the '+?' is applied to. It seems to be the way this regex behaved. Or does the regex see its going to fail with the empty first bracket pair, and so tries to advance to somehow find a match? This seems pretty vague. I thought a regex first looks for the next character beyond the expression the '+?' is applied to, before it consumes any characters? That is the way the second regex, '.*?', behaved. Hope it was clear enough. :-) -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Behavior of minimal when applied to - {1,}? ot to - {0,}?
CC == Chris Charley char...@pulsenet.com writes: CC #!/usr/bin/perl CC use strict; CC use warnings; CC $_ = [][12/21/10 18:39:22] [oasetup] [oasetup] [INFO] Installing the CC HPOvXpl package...; CC for my $re (qw{ ^\[(.+?)\] ^\[(.*?)\] }) { CCmy ($dt) = /$re/ or die Horrible death\n;; CCprint $re, ' ', '$dt', \n; CC } CC __END__ CC C:\Old_Data\perlpperl t5.pl CC ^\[(.+?)\] '][12/21/10 18:39:22' CC ^\[(.*?)\] '' CC C:\Old_Data\perlp CC My question in the code above is the '.+?' behavior. I had guessed CC that it would attempt to match the empty brackets and fail, CC (because it requires 1 or more characters). Instead, it captures CC the right bracket and the left opening bracket and contents (date) CC of the second bracket pair. the regex is working as you coded it. CC Does the regex first consume a character before checking the next CC character to see if it is the first one *after* the expression the '+?' is CC applied to. It seems to be the way this regex behaved. if a regex fails, it bumps the char pointer to the next data char and starts over. but you have an anchor there so it must match at the beginning. so it matches the leading [ as you ask. then it grabs until it sees text followed by a ]. you got what you asked for. CC Or does the regex see its going to fail with the empty first CC bracket pair, and so tries to advance to somehow find a match? CC This seems pretty vague. nope. it is just what you said. the anchor forces it to grab the ] as it satisfies the grab. and without the anchor it still grabs the same thing since it does match from the leading [ to a closing ] with text inside. the better way to grab inside delimiters is to use a negated char class of the closing delimiter. this grabs from a [ all the chars but a ] to the next ]. this works: qr{\[([^]]+)\]} i used qr's instead of qw's but it comes out the same. uri -- Uri Guttman -- u...@stemsystems.com http://www.sysarch.com -- - Perl Code Review , Architecture, Development, Training, Support -- - Gourmet Hot Cocoa Mix http://bestfriendscocoa.com - -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Behavior of minimal when applied to - {1,}? ot to - {0,}?
On 01/02/2011 02:30, Chris Charley wrote: #!/usr/bin/perl use strict; use warnings; $_ = [][12/21/10 18:39:22] [oasetup] [oasetup] [INFO] Installing the HPOvXpl package...; for my $re (qw{ ^\[(.+?)\] ^\[(.*?)\] }) { my ($dt) = /$re/ or die Horrible death\n;; print $re, ' ', '$dt', \n; } __END__ C:\Old_Data\perlpperl t5.pl ^\[(.+?)\] '][12/21/10 18:39:22' ^\[(.*?)\] '' C:\Old_Data\perlp My question in the code above is the '.+?' behavior. I had guessed that it would attempt to match the empty brackets and fail, (because it requires 1 or more characters). Instead, it captures the right bracket and the left opening bracket and contents (date) of the second bracket pair. Does the regex first consume a character before checking the next character to see if it is the first one *after* the expression the '+?' is applied to. It seems to be the way this regex behaved. Or does the regex see its going to fail with the empty first bracket pair, and so tries to advance to somehow find a match? This seems pretty vague. I thought a regex first looks for the next character beyond the expression the '+?' is applied to, before it consumes any characters? That is the way the second regex, '.*?', behaved. Hope it was clear enough. :-) Hey Chris /.+?/ requires at least one character, so /^\[.+?\]/ will need at least three characters for a match. The engine will try to match /^\[.\]/ and fail, then /^\[..\]/, then /^\[...\]/ and so on. Perl doesn't care that the object string's second character is a ']' - all it has to do is match /./ and that will do fine. This process continues until the pattern is long enough to reach the first closing square bracket it sees, and so comsumes the date/time field to get there. /.*?/ will match zero characters, so the initial [] fits the bill immediately. The ? doesn't change the lower bound of the character count - it simply says to match as few as possible. /.{2,4}/ will match four characters, while /.{2,4}?/ will match two. HTH, Rob -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Help with script How to prepend 2 lines instead of 1
Using the script below I need to add a second line with the following text: STAGEHDR|Barcoded #!perl use strict; use warnings; my $file = 'path/to/Access.csv'; my $newline = ENTHDR|1|3.0; { local @ARGV = ($file); local $^I = '.bac'; while(){ if ($. == 1) { print $newline$/; } else { print; } } } -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Help with script How to prepend 2 lines instead of 1
Hi Steve, On Thursday 20 Jan 2011 21:10:39 steve1040 wrote: Using the script below I need to add a second line with the following text: STAGEHDR|Barcoded #!perl use strict; use warnings; my $file = 'path/to/Access.csv'; my $newline = ENTHDR|1|3.0; { local @ARGV = ($file); local $^I = '.bac'; while(){ Please avoid such games in any half-serious code. While they are useful from the command line, they won't work properly within a larger code. See my response to your earlier post with a proper way to do that and some other pointers. Regards, Shlomi Fish -- - Shlomi Fish http://www.shlomifish.org/ Optimising Code for Speed - http://shlom.in/optimise Chuck Norris can make the statement This statement is false a true one. Please reply to list if it's a mailing list post - http://shlom.in/reply . -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Help with script How to prepend 2 lines instead of 1
On 20/01/2011 19:10, steve1040 wrote: Using the script below I need to add a second line with the following text: STAGEHDR|Barcoded #!perl use strict; use warnings; my $file = 'path/to/Access.csv'; my $newline = ENTHDR|1|3.0; { local @ARGV = ($file); local $^I = '.bac'; while(){ if ($. == 1) { print $newline$/; } else { print; } } } Hi Steve You seem to have ignored the help you were offered when you last posted this problem. The code you have here (apart from the misgivings that Shlomi has expressed) will /replace/ the first line of the input file with the given string. Is that what you want, or do you need to add (prepend) them as you said previously? You have already been shown code that will do the latter; do you need a different solution? - Rob -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
AW:FW: 1--.
Dear, I have tried to purchase some products from a business company, I have attracted by high quality products, low price and enthusiastic services, I think if you are free, you can go to see: styleele.com ,picking your interesting. ~--. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Can't use string 1 as HASH ref while strict refs in use
On 20 July 2010 04:40, Mimi Cafe mimic...@googlemail.com wrote: I passed a has reference to my sub and tried dereferencing it within the sub and get an exception Can't use string (1) as HASH ref while strict refs in use. my %mail_parameters = ( 'Fname' = $nickname_db_exist[1], 'Lname' = $nickname_db_exist[2], 'E-mail' = $reset_email, 'Subject' = Your $site_name Password Reset, ); # Send the requested information. Mail_worker(\%mail_parameters); Sub mail_worker { $received_arg = @_; %params = %$received_arg;# Can't use string 1 as HASH ref while strict refs in use . .. I hope Uri will forgive me but I will expand a little. $received_arg = @_; You want to shift the argument list but you are actually assigned the argument array to a scalar value and that will render it's size (1). You passed Mail_worker a reference to a hash so that hash is now a single scalar value. Then in your subroutine (called mail_worker, you dropped the case in your example) after assigning the length of the argument list to $recieved_arg you attempt to deference it, causing the error. You could have kept the hash as a reference sub Mail_worker { my $recieved_arg = shift; print User first name is $recieved_arg-{Fname}\n; . } You could have kept it as a hash but that's passing by value and considered slightly poor practice as your passing more data that you need. One more option would be to use a named parameter list Mail_worker(Fname = $nickname_db_exist[1], Lname = $nickname_db_exist[2], 'E-mail' = $reset_email, 'Subject' = Your $site_name Password Reset, ); sub Mail_worker { my %args = @_ print User first name is $recieved_arg{Fname}\n } I hope that helps, Dp. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
RE: Can't use string 1 as HASH ref while strict refs in use
Oh, yes! I see. I went through the codes several times but did not pick that mistake for some reason. Perhaps I was working too late in the night :-) This works: $received_arg = shift; Thanks = -Original Message- = From: Uri Guttman [mailto:u...@stemsystems.com] = Sent: 20 July 2010 04:44 = To: Mimi Cafe = Cc: 'Perl Beginners' = Subject: Re: Can't use string 1 as HASH ref while strict refs in use = = MC == Mimi Cafe mimic...@googlemail.com writes: = = MC $received_arg = @_; = = read perldoc perldata and see what happens when you assign an array to = a = scalar. you don't get what you think you are getting. context is VERY = important to learn in perl and this is a critical context situation = that = is very common. i won't give you the answer since reading about it = will = strengthten your learning about this. = = uri = = -- = Uri Guttman -- u...@stemsystems.com = http://www.sysarch.com -- = - Perl Code Review , Architecture, Development, Training, Support = -- = - Gourmet Hot Cocoa Mix http://bestfriendscocoa.com -- = --- -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Can't use string 1 as HASH ref while strict refs in use
D == Dermot paik...@gmail.com writes: D I hope Uri will forgive me but I will expand a little. partially forgive! :) D $received_arg = @_; D You want to shift the argument list but you are actually assigned the D argument array to a scalar value and that will render it's size (1). D You passed Mail_worker a reference to a hash so that hash is now a D single scalar value. Then in your subroutine (called mail_worker, you D dropped the case in your example) after assigning the length of the D argument list to $recieved_arg you attempt to deference it, causing D the error. You could have kept the hash as a reference why do you say she wants to shift @_? that is the lesser style of getting an arg from @_. the better way IMNSHO is assigning to a list. shift is slower, doesn't work well for multiple args (one shift per statement) and it modifies @_ unnecessarily. there are times when it is useful but the primary method should be a list assignment. uri -- Uri Guttman -- u...@stemsystems.com http://www.sysarch.com -- - Perl Code Review , Architecture, Development, Training, Support -- - Gourmet Hot Cocoa Mix http://bestfriendscocoa.com - -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Can't use string 1 as HASH ref while strict refs in use
I passed a has reference to my sub and tried dereferencing it within the sub and get an exception Can't use string (1) as HASH ref while strict refs in use. my %mail_parameters = ( 'Fname' = $nickname_db_exist[1], 'Lname' = $nickname_db_exist[2], 'E-mail' = $reset_email, 'Subject' = Your $site_name Password Reset, ); # Send the requested information. Mail_worker(\%mail_parameters); Sub mail_worker { $received_arg = @_; %params = %$received_arg;# Can't use string 1 as HASH ref while strict refs in use . .. } Regards -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Can't use string 1 as HASH ref while strict refs in use
MC == Mimi Cafe mimic...@googlemail.com writes: MC $received_arg = @_; read perldoc perldata and see what happens when you assign an array to a scalar. you don't get what you think you are getting. context is VERY important to learn in perl and this is a critical context situation that is very common. i won't give you the answer since reading about it will strengthten your learning about this. uri -- Uri Guttman -- u...@stemsystems.com http://www.sysarch.com -- - Perl Code Review , Architecture, Development, Training, Support -- - Gourmet Hot Cocoa Mix http://bestfriendscocoa.com - -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: \1 in character class?
Wow, an impressive set of responses -- thanks Erez, Chas, Chris, C., Shawn, and Jennifer. I think most of the response pointed to non-greedy matches, is that right? Are those deprecated or discouraged? Thanks again. - Bryan On Wed, Jul 14, 2010 at 00:50, C.DeRykus dery...@gmail.com wrote: snip s/(\w+)\s/$1nbsp;/g; snip Neat. Using the \K construct available in 5.10, you can even eliminate the need for the capture: s/ \w+ \K \s /nbsp;/gx; snip Yeah, but both of these are fragile, the following string won't work: data: this, is a string more: this is another -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: \1 in character class?
BRH == Bryan R Harris bryan_r_har...@raytheon.com writes: BRH I think most of the response pointed to non-greedy matches, is BRH that right? Are those deprecated or discouraged? nope, they are very useful and stable (not experimental in the least). non-greedy vs greedy is one of those things that newbies almost never seem to find on their own but get it when told about them. this is why i keep saying to rtfm all the regex docs as there is a host of useful easy to learn things in them. when i say docs, i mean perlrequick, perlretut and perlre. each has a different target but all are useful. and when you read a doc for the first time (or repeat times) read it ALL the way through and skip/skim the parts you may not get. just knowing about a feature a little and before you ever use it helps when you really need it. non-greedy is well documented but you have to read about it. uri -- Uri Guttman -- u...@stemsystems.com http://www.sysarch.com -- - Perl Code Review , Architecture, Development, Training, Support -- - Gourmet Hot Cocoa Mix http://bestfriendscocoa.com - -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: \1 in character class?
On Jul 14, 2:59 pm, chas.ow...@gmail.com (Chas. Owens) wrote: On Wed, Jul 14, 2010 at 00:50, C.DeRykus dery...@gmail.com wrote: snip s/(\w+)\s/$1nbsp;/g; snip Neat. Using the \K construct available in 5.10, you can even eliminate the need for the capture: s/ \w+ \K \s /nbsp;/gx; snip Yeah, but both of these are fragile, the following string won't work: data: this, is a string more: this is another Agreed this isn't the most robust but there wasn't a complete spec so simple quoted string might throw someone. And I notice the OP's original despace sub for instance contained: s/\s/nbsp;/g; But, one of the solutions morphed that to: s/ /nbsp;/g which, might or might not, be right either. -- Charles DeRykus -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: \1 in character class?
- Original Message - From: Bryan R Harris bryan_r_har...@raytheon.com Subject: \1 in character class? I'm trying to temporarily deal with simple quoted strings by turning: data: this is a string more: this is another into... data: thisnbsp;isnbsp;anbsp;string more: thisnbsp;isnbsp;another TIA. - Bryan Here is a way using tbe module Regexp::Common. #!/usr/bin/perl use strict; use warnings; use Regexp::Common; while (DATA) { s/($RE{quoted})/ (my $s=$1) =~ s[\s][nbsp;]g; $s/egx; print; } __DATA__ data: this is a string more: this is another -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: \1 in character class?
On Jul 13, 8:09 am, jonesharring...@gmail.com (Jennifer Jones Harrington) wrote: How about... #!/usr/bin/perl use warnings; $_ = data: \this is a string\ more: \this is another\; s/(\w+)\s/$1nbsp;/g; print $_\n; It prints: data: thisnbsp;isnbsp;anbsp;string more: thisnbsp;isnbsp;another Neat. Using the \K construct available in 5.10, you can even eliminate the need for the capture: s/ \w+ \K \s /nbsp;/gx; -- Charles DeRykus s/ -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: \1 in character class?
On Wed, Jul 14, 2010 at 00:50, C.DeRykus dery...@gmail.com wrote: snip s/(\w+)\s/$1nbsp;/g; snip Neat. Using the \K construct available in 5.10, you can even eliminate the need for the capture: s/ \w+ \K \s /nbsp;/gx; snip Yeah, but both of these are fragile, the following string won't work: data: this, is a string more: this is another -- Chas. Owens wonkden.net The most important skill a programmer can have is the ability to read. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
\1 in character class?
I'm trying to temporarily deal with simple quoted strings by turning: data: this is a string more: this is another into... data: thisnbsp;isnbsp;anbsp;string more: thisnbsp;isnbsp;another I thought this would work: s/(['])([^\1]*)\1/${1}.despace($2).$1/gse; sub despace { my $t = shift; $t =~ s/\s/nbsp;/g; return $t; } ... but it doesn't. It looks like the [^\1]* in the regex isn't working right. I can always split it into two, but I'm curious why the above doesn't work. TIA. - Bryan -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: \1 in character class?
How about... #!/usr/bin/perl use warnings; $_ = data: \this is a string\ more: \this is another\; s/(\w+)\s/$1nbsp;/g; print $_\n; It prints: data: thisnbsp;isnbsp;anbsp;string more: thisnbsp;isnbsp;another On Tue, Jul 13, 2010 at 6:00 AM, Bryan R Harris bryan_r_har...@raytheon.com wrote: I'm trying to temporarily deal with simple quoted strings by turning: data: this is a string more: this is another into... data: thisnbsp;isnbsp;anbsp;string more: thisnbsp;isnbsp;another I thought this would work: s/(['])([^\1]*)\1/${1}.despace($2).$1/gse; sub despace { my $t = shift; $t =~ s/\s/nbsp;/g; return $t; } ... but it doesn't. It looks like the [^\1]* in the regex isn't working right. I can always split it into two, but I'm curious why the above doesn't work. TIA. - Bryan -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: \1 in character class?
On 10-07-13 06:00 AM, Bryan R Harris wrote: I'm trying to temporarily deal with simple quoted strings by turning: data: this is a string more: this is another into... data: thisnbsp;isnbsp;anbsp;string more: thisnbsp;isnbsp;another I thought this would work: s/(['])([^\1]*)\1/${1}.despace($2).$1/gse; sub despace { my $t = shift; $t =~ s/\s/nbsp;/g; return $t; } ... but it doesn't. It looks like the [^\1]* in the regex isn't working right. I can always split it into two, but I'm curious why the above doesn't work. Because [] define a character set; everything inside it is a character. That means it does not expand \1. Try: s/(['])(.*?)\1/${1}.despace($2).$1/gse; This will set $2 to the minimum number of characters between the quotes. For details, see: perldoc perlretut perldoc perlre -- Just my 0.0002 million dollars worth, Shawn Programming is as much about organization and communication as it is about coding. The secret to great software: Fail early often. Eliminate software piracy: use only FLOSS. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: \1 in character class?
On 13 July 2010 13:00, Bryan R Harris bryan_r_har...@raytheon.com wrote: I thought this would work: s/(['])([^\1]*)\1/${1}.despace($2).$1/gse; ... but it doesn't. It looks like the [^\1]* in the regexp isn't working right. Character classes (characters inside square brackets - []) in regexp notation, interpret whatever is inside sometimes differently than it would be interpreted otherwise, with backslash taking a different meaning so \1,\2 back-references doesn't have the special meaning it has outside of the square brackets. There are other hijinks regarding backspace functionality inside character classes, which are sporadically documented in the different regexp descriptions and manuals. For what you need, I suggest a negative lookahead, i.e. (?!\1) for zero-length lookahead. -- Erez Observations, not opinions -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: \1 in character class?
On Tue, Jul 13, 2010 at 06:00, Bryan R Harris bryan_r_har...@raytheon.com wrote: I'm trying to temporarily deal with simple quoted strings by turning: data: this is a string more: this is another into... data: thisnbsp;isnbsp;anbsp;string more: thisnbsp;isnbsp;another I thought this would work: s/(['])([^\1]*)\1/${1}.despace($2).$1/gse; sub despace { my $t = shift; $t =~ s/\s/nbsp;/g; return $t; } ... but it doesn't. It looks like the [^\1]* in the regex isn't working right. I can always split it into two, but I'm curious why the above doesn't work. \1 in a character class does work, it just doesn't mean what you think it means: perl -le 'print chr(1) =~ /[\1]/ ? match : no_match' In a character class, escaped numbers 1-7, 10-77, 100-777, and 001-777 are octal escapes that are replaced with the character whose ordinal number is the escaped value (in octal), so \12 is \012 is \x{0a} is ord(10) is linefeed in ASCII. Outside of a character class in a regex, the escaped numbers 1 - 9 refer to either captures if there are that many captures or an octal escape if there aren't that many captures. So, in /(a)\1/ the \1 refers the value of the first capture, but /a\1/ matches a followed by chr(1) (start of header in ASCII). Octal escapes really shouldn't be used anymore since we have the \x{NUM} quoting mechanism is much more flexible. As for backreferences, if you are using Perl 5.10 or later you have \g{N}: \g{N} replaces \N for backreferences and has the added benefit that \g{-1} refers to the last capture before it, \g{-2} referes to the next to last capture before it, and so on. This means that /(a)\g{-1}(b)\g{-2}\g{-1}/ is the same as /aabab/. To make your substitution work, you need to say #!/usr/bin/perl use strict; use warnings; my $s = 'data: this is a string more: this is another'; $s =~ s{ (.*?) }{ my $temp = $1; $temp =~ s/ /nbsp;/g; qq/$temp/; }xgse; print $s\n; or the more compact: #!/usr/bin/perl use strict; use warnings; sub despace { my $s = shift; $s =~ s/ /nbsp;/g; return $s; } my $s = 'data: this is a string more: this is another'; $s =~ s/(.*?)/despace qq{$1}/gse; print $s\n; -- Chas. Owens wonkden.net The most important skill a programmer can have is the ability to read. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: \1 in character class?
On 13 July 2010 18:16, Shawn H Corey shawnhco...@gmail.com wrote: Because [] define a character set; everything inside it is a character. That means it does not expand \1. That's not entirely correct. Character classes recognize variables, escaped characters and some other regexp notation, but not \1 back-references -- Erez Observations, not opinions -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: \1 in character class?
On Jul 13, 2010, at 11:32, Erez Schatz moonb...@gmail.com wrote: On 13 July 2010 18:16, Shawn H Corey shawnhco...@gmail.com wrote: Because [] define a character set; everything inside it is a character. That means it does not expand \1. That's not entirely correct. Character classes recognize variables, escaped characters and some other regexp notation, but not \1 back-references -- Erez Observations, not opinions -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/ It does recognize them, it just recognizes them as octal escapes. [\8] is even more fun. It matches chr(0) or the character 8. There is some work going on in perl 5.13 to fix this (or at least give a better warning message). -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
What is the difference between: 'my $var = 1' vs. 'my ( $var ) = 1'?
At the introductory level it seems like I have often seen code like this: use strict; my $var = 1; And as I review other peoples' scripts I have often encountered code like this: use strict; my ( $this, $that, $the_other ); Which I interpreted as a mechanism to declare a number of scalar variables with a minimum of typing. But lately I've been seeing this syntax and I was wondering if it was fundamentally different (and somehow more desirable): use strict; my ( $var ) = 1; As if $var is being declared in a list context; what, if anything, do I get by including parentheses when declaring a single variable? Thanks, --Marc
Re: What is the difference between: 'my $var = 1' vs. 'my ( $var ) = 1'?
On Tue, Apr 20, 2010 at 2:23 PM, Marc Perry marcperrys...@gmail.com wrote: As if $var is being declared in a list context; what, if anything, do I get by including parentheses when declaring a single variable? I'm new to this myself, but it appears to alter the context of the statement. Take the following: #!/usr/bin/env perl use strict; use warnings; $, = $\ = \n; my @a = (element1, element2, element3); my $x = @a; my ( $y ) = @a; print $x, $y; # EOF The output should be: 3 element1 In the first case, the context is scalar, which results in the element count being assigned to $x instead of the element(s). In the second case, the context is list context, I think, which results in the first element of the array being assigned to the variable $y. I'm not clear on how to properly explain this, but to me it appears to make a list of lvalues (assignables) and then moves the data from corresponding positions on the right side of the equals sign to the left. Again, there's probably a much better (and more correct) way to explain that. ;) In other words, using or not using parenthesis can be context sensitive so you need to know what you're doing with it. If you're just declaring a normal variable, as in your example where you assign it 1, then it doesn't seem to technically matter which you use, but you're probably preferred to NOT use parenthesis because it's unnecessary and might even be confusing if you are (and if the context of the right-side changes then the meaning will change). ??? `perldoc perldata' appears to cover context somewhat: http://perldoc.perl.org/perldata.html#Context -- Brandon McCaig bamcc...@gmail.com V zrna gur orfg jvgu jung V fnl. Vg qbrfa'g nyjnlf fbhaq gung jnl. Castopulence Software http://www.castopulence.org/ bamcc...@castopulence.org -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: What is the difference between: 'my $var = 1' vs. 'my ( $var ) = 1'?
On 4/20/10 Tue Apr 20, 2010 11:23 AM, Marc Perry marcperrys...@gmail.com scribbled: At the introductory level it seems like I have often seen code like this: use strict; my $var = 1; And as I review other peoples' scripts I have often encountered code like this: use strict; my ( $this, $that, $the_other ); Which I interpreted as a mechanism to declare a number of scalar variables with a minimum of typing. But lately I've been seeing this syntax and I was wondering if it was fundamentally different (and somehow more desirable): use strict; my ( $var ) = 1; As if $var is being declared in a list context; what, if anything, do I get by including parentheses when declaring a single variable? You put the left-hand side into list context, which forces the right-hand side of the assignment into list context. Perl will interpolate the scalar value 1 into a list for you, yielding the one-element list (1). The first element of the right-hand side (1) will then be assigned to the first element of the left-hand side ($var). Therefore, you gain nothing except to confuse your readers. That line is better written as: my $var = 1; -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: 1-line datafile, need data for another routine
Rob Dixon wrote: Chris Coggins wrote: I posted a question to this list yesterday from the google groups interface, asking for help with the following. I have since tried to post additional details in replies to that message using the google groups site and none of my posts have shown up on the list so let's try this again the right way. I have a datafile with 1 line of data, 30 numbers delimited by tildes. (Sample code below only uses 4 numbers to save time) I need to open this file, grab this line of data, split it into individual numbers, perform some simple math (addition) on each number, and then put the new values back into the datafile, replacing the original data that was there. I neglected to mention in my original post that I need to access these new values elsewhere in the script to perform additional math functions with them. I've tried several variations of the code below, including using arrays, and none of them got through without the script failing. The new datafile gets written, but it merely contains a ~. The errors I get are use of uninitialized values in such and such line and variables needs explicit package name. When the script does run, the variables lose their values as soon as I close the file after inhaling it, making all the rest of the actions in the subroutine futile. the datafile used below initially contains 30 values that were written previously, and this has been verified over and over. sub newValues { my($file) = shift; open(FILE, $file) or die(Unable to open data file.); while (FILE) { my($a,$b,$c,$d) = split(/~/, $_); $a = $a+$previousarray[4]; # I've tried to perform this math action after close(FILE) and get the same result - failure. $b = $b+$previousarray[7]; $c = $c+$previousarray[0]; } close(FILE); open(FILE, $file) || die (unable to open file); print FILE ($a~$b~$c \n); close(FILE); } #end sub Now my datafile just contains a single tilde and no values. I've also tried to bring the original data from the datafile into my(@array) and get the same errors. Keep in mind I need other subroutines to be able use these new values, but these local variables lose their values once the file is closed. I've also tried to declare them as global variables but I'm not doing something right because the script won't execute. I really need some help figuring this out if somebody would be kind enough to help a novice. Hello Chris Your lexical variables $a, $b, $c are local to the 'while' block, and do not exist outside it. Error Global symbol xx requires explicit package name is because the variable is not declared. Error Use of uninitialized value... is because Perl uses a value of 'undef' where variables are missing. As an aside it is bad form to use meaningless variable names, and $a and $b are special names that are used by core Perl so should be avoided. Also it is prefereable to use lexical file handles and the three-argument form of 'open', and incorporating the standard variable $! into the die string will give valuable information about why the operation failed. Declaring your variables outside the 'while' loop would fix your problem, but as you are interested only in the first line of the file it is as well to remove the loop altogether. Take a look at the code below and see if it meets your requirements. HTH, Rob sub newValues { my $file = shift; open my $data, '', $file or die Unable to open data file: $!; my $line = $data; close $data; my @data = split /~/, $line; die Invalid data format if @data 3; $data[0] += $previousarray[4]; $data[1] += $previousarray[7]; $data[2] += $previousarray[0]; open my $out, '', $file or die Unable to open output file: $!; print $out join('~', @data[0,1,2]), \n; close $out or die Failed to close output file: $!; } Rob, thank you very much. This worked perfectly, unless my datafile is empty at the start. Easiest fix was inserting 30 zero-tildes into the file. I have a couple other snags if yall are willing to tolerate the questions. 1. another script uses data passed into it from an html form. Some of the fields are empty, and my print report file subroutine prints the empty variables because I don't know how to filter them out, and they need to be removed from the report. Can someone give me the perfectly formed if statement that lets me skip over the one or two empty variables during the print action? The data being printed to the file is stored in an array. See code below. print FILE (Report summary: $taskarray[0] \n); #this value is good print FILE (Data for task 3: $taskarray[3] \n); #this value is good print FILE (Data for task 7: $taskarray[7] \n); #this value is empty, don't print this data print FILE (Data for task 2: $taskarray[2] \n); #this value is empty, don't print this data print FILE (Data for task 11: $taskarray[11] \n); #this value is good but needs to be modified, see #2 below 2. Some of the data being
Re: 1-line text file with numbers, need to add to them
On 2/4/10, Chris cacogg...@gmail.com wrote: On Feb 4, 10:59 am, shlo...@iglu.org.il (Shlomi Fish) wrote: Hi Chris! Have you visitedhttp://perl-begin.org/yet and read a good introductory book or tutorial? On Thursday 04 Feb 2010 09:27:32 Chris wrote: I need some help with this problem. I've got a text file datafile with 1 line of data comprised of 30 different numbers delimited with ~s. I need to open this file, grab this line of data, split it into individual numbers, perform some simple math (addition) on each number, and then put the new values back into the datafile, replacing the original data that was there. I have tried for two days to figure out what I'm doing wrong, but I keep getting needs a package name errors for every variable nomenclature I try to work with. I've declare arrays and variables until my fingers are numb and nothing is working. I'm using Perl 5.008 if that matters. You need to declare variables using my. Can you show us what you have so far? Regards, Shlomi Fish Can somebody please help? Yes I have read several tutorials, and have a basic understanding of how to open a file and read the data into an array. The problem I run into is that once I close the file and perform my math functions and re-open the file to write the data to, the data is gone. Empty values are written to the file, making the file itself empty. I need to know the proper nomenclature for the arrays and variables so that the values of variables/elements are static for the next action. Here's one of the methods I tried to use that failed: #open file, get data, close file open(FILE, datafile.txt) or die(Unable to open data file.); while (FILE) { my($a,$b,$c) = split(/~/, $_); } close(FILE); #perform math $a = $a+$previousarray[0]; #add the value of $a and the value of an element in a previous array $b = $b+$previousarray[1]; $c = $c+$previousarray[2]; #write new values to the datafile open(FILE, datafile.txt) or die (unable to open file.); print FILE ($a~); print FILE ($b~); print FILE ($c~); close(FILE); #end of problem section The above produces an empty datafile. I have tried to declare an explicit array for the file data using the following: open(FILE, datafile.txt) or die(Unable to open data file.); @values=FILE; close(FILE); foreach $element (@values) { ($a,$b,$c) = split(/~/, $element); $a = $a+$previousarray[0]; $b = $b+$previousarray[1]; $c = $c+$previousarray[2]; #then open the datafile and write new values. I keep getting use of unititialized values errors, and needs explicit package name errors, and an empty datafile. That's why I came to this forum for help. I also neglected to note in my original post that I need to access these new values elsewhere in the script. I'm not sure why you write the new values to a file. You could leave the new values in an array, then later in your program you could retrieve the new values from the array. data1.txt 0~s10~s100 use strict; use warnings; use 5.010; open my $IN_FILE, '', 'data1.txt' or die couldn't open data1.txt for reading: $!; chomp (my $line = $IN_FILE); close $IN_FILE; my @numbers = split /~s/, $line; say @numbers; #0 10 100 for (@numbers) { $_ += 1; } say @numbers; #1 11 101 my $output = join '~s', @numbers; say $output; #1~s11~s101 open my $OUT_FILE, '', 'data1.txt' or die couldn't open data1.txt for writing: $!; say $OUT_FILE $output; close $OUT_FILE; data1.txt - 1~s11~s101 print() is your friend. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: 1-line datafile, need data for another routine
On 2/6/10, Chris Coggins cacogg...@cox.net wrote: Rob Dixon wrote: Chris Coggins wrote: I posted a question to this list yesterday from the google groups interface, asking for help with the following. I have since tried to post additional details in replies to that message using the google groups site and none of my posts have shown up on the list so let's try this again the right way. I have a datafile with 1 line of data, 30 numbers delimited by tildes. (Sample code below only uses 4 numbers to save time) I need to open this file, grab this line of data, split it into individual numbers, perform some simple math (addition) on each number, and then put the new values back into the datafile, replacing the original data that was there. I neglected to mention in my original post that I need to access these new values elsewhere in the script to perform additional math functions with them. I've tried several variations of the code below, including using arrays, and none of them got through without the script failing. The new datafile gets written, but it merely contains a ~. The errors I get are use of uninitialized values in such and such line and variables needs explicit package name. When the script does run, the variables lose their values as soon as I close the file after inhaling it, making all the rest of the actions in the subroutine futile. the datafile used below initially contains 30 values that were written previously, and this has been verified over and over. sub newValues { my($file) = shift; open(FILE, $file) or die(Unable to open data file.); while (FILE) { my($a,$b,$c,$d) = split(/~/, $_); $a = $a+$previousarray[4]; # I've tried to perform this math action after close(FILE) and get the same result - failure. $b = $b+$previousarray[7]; $c = $c+$previousarray[0]; } close(FILE); open(FILE, $file) || die (unable to open file); print FILE ($a~$b~$c \n); close(FILE); } #end sub Now my datafile just contains a single tilde and no values. I've also tried to bring the original data from the datafile into my(@array) and get the same errors. Keep in mind I need other subroutines to be able use these new values, but these local variables lose their values once the file is closed. I've also tried to declare them as global variables but I'm not doing something right because the script won't execute. I really need some help figuring this out if somebody would be kind enough to help a novice. Hello Chris Your lexical variables $a, $b, $c are local to the 'while' block, and do not exist outside it. Error Global symbol xx requires explicit package name is because the variable is not declared. Error Use of uninitialized value... is because Perl uses a value of 'undef' where variables are missing. As an aside it is bad form to use meaningless variable names, and $a and $b are special names that are used by core Perl so should be avoided. Also it is prefereable to use lexical file handles and the three-argument form of 'open', and incorporating the standard variable $! into the die string will give valuable information about why the operation failed. Declaring your variables outside the 'while' loop would fix your problem, but as you are interested only in the first line of the file it is as well to remove the loop altogether. Take a look at the code below and see if it meets your requirements. HTH, Rob sub newValues { my $file = shift; open my $data, '', $file or die Unable to open data file: $!; my $line = $data; close $data; my @data = split /~/, $line; die Invalid data format if @data 3; $data[0] += $previousarray[4]; $data[1] += $previousarray[7]; $data[2] += $previousarray[0]; open my $out, '', $file or die Unable to open output file: $!; print $out join('~', @data[0,1,2]), \n; close $out or die Failed to close output file: $!; } Rob, thank you very much. This worked perfectly, unless my datafile is empty at the start. Easiest fix was inserting 30 zero-tildes into the file. I have a couple other snags if yall are willing to tolerate the questions. 1. another script uses data passed into it from an html form. Some of the fields are empty, and my print report file subroutine prints the empty variables because I don't know how to filter them out, and they need to be removed from the report. Can someone give me the perfectly formed if statement that lets me skip over the one or two empty variables during the print action? The data being printed to the file is stored in an array. See code below. print FILE (Report summary: $taskarray[0] \n); #this value is good print FILE (Data for task 3: $taskarray[3] \n); #this value is good print FILE (Data for task 7: $taskarray[7] \n); #this value is empty, don't print this data print FILE (Data for task 2: $taskarray[2] \n); #this value is empty, don't print this data print FILE (Data for task 11: $taskarray[11] \n
Re: 1-line datafile, need data for another routine
At 5:48 AM -0500 2/6/10, Chris Coggins wrote: 1. another script uses data passed into it from an html form. Some of the fields are empty, and my print report file subroutine prints the empty variables because I don't know how to filter them out, and they need to be removed from the report. Can someone give me the perfectly formed if statement that lets me skip over the one or two empty variables during the print action? The data being printed to the file is stored in an array. See code below. print FILE (Report summary: $taskarray[0] \n); #this value is good print FILE (Data for task 3: $taskarray[3] \n); #this value is good print FILE (Data for task 7: $taskarray[7] \n); #this value is empty, don't print this data print FILE (Data for task 2: $taskarray[2] \n); #this value is empty, don't print this data print FILE (Data for task 11: $taskarray[11] \n); #this value is good but needs to be modified, see #2 below If a scalar variable is empty, i.e. is either undef or an empty string '', it will have a false value in a logical expression. Therefore, you can test the value of the variable and only print it if it is true: if( $string ) { print $string\n; } or the shorter equivalent: print $string\n if $string; -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: 1-line datafile, need data for another routine
I posted a question to this list yesterday from the google groups interface, asking for help with the following. I have since tried to post additional details in replies to that message using the google groups site and none of my posts have shown up on the list so let's try this again the right way. I have a datafile with 1 line of data, 30 numbers delimited by tildes. (Sample code below only uses 4 numbers to save time) I need to open this file, grab this line of data, split it into individual numbers, perform some simple math (addition) on each number, and then put the new values back into the datafile, replacing the original data that was there. I neglected to mention in my original post that I need to access these new values elsewhere in the script to perform additional math functions with them. I've tried several variations of the code below, including using arrays, and none of them got through without the script failing. The new datafile gets written, but it merely contains a ~. The errors I get are use of uninitialized values in such and such line and variables needs explicit package name. When the script does run, the variables lose their values as soon as I close the file after inhaling it, making all the rest of the actions in the subroutine futile. the datafile used below initially contains 30 values that were written previously, and this has been verified over and over. sub newValues { my($file) = shift; open(FILE, $file) or die(Unable to open data file.); while (FILE) { my($a,$b,$c,$d) = split(/~/, $_); $a = $a+$previousarray[4]; # I've tried to perform this math action after close(FILE) and get the same result - failure. $b = $b+$previousarray[7]; $c = $c+$previousarray[0]; } close(FILE); open(FILE, $file) || die (unable to open file); print FILE ($a~$b~$c \n); close(FILE); } #end sub Now my datafile just contains a single tilde and no values. I've also tried to bring the original data from the datafile into my(@array) and get the same errors. Keep in mind I need other subroutines to be able use these new values, but these local variables lose their values once the file is closed. I've also tried to declare them as global variables but I'm not doing something right because the script won't execute. I really need some help figuring this out if somebody would be kind enough to help a novice. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: 1-line text file with numbers, need to add to them
On Feb 4, 10:59 am, shlo...@iglu.org.il (Shlomi Fish) wrote: Hi Chris! Have you visitedhttp://perl-begin.org/yet and read a good introductory book or tutorial? On Thursday 04 Feb 2010 09:27:32 Chris wrote: I need some help with this problem. I've got a text file datafile with 1 line of data comprised of 30 different numbers delimited with ~s. I need to open this file, grab this line of data, split it into individual numbers, perform some simple math (addition) on each number, and then put the new values back into the datafile, replacing the original data that was there. I have tried for two days to figure out what I'm doing wrong, but I keep getting needs a package name errors for every variable nomenclature I try to work with. I've declare arrays and variables until my fingers are numb and nothing is working. I'm using Perl 5.008 if that matters. You need to declare variables using my. Can you show us what you have so far? Regards, Shlomi Fish Can somebody please help? Yes I have read several tutorials, and have a basic understanding of how to open a file and read the data into an array. The problem I run into is that once I close the file and perform my math functions and re-open the file to write the data to, the data is gone. Empty values are written to the file, making the file itself empty. I need to know the proper nomenclature for the arrays and variables so that the values of variables/elements are static for the next action. Here's one of the methods I tried to use that failed: #open file, get data, close file open(FILE, datafile.txt) or die(Unable to open data file.); while (FILE) { my($a,$b,$c) = split(/~/, $_); } close(FILE); #perform math $a = $a+$previousarray[0]; #add the value of $a and the value of an element in a previous array $b = $b+$previousarray[1]; $c = $c+$previousarray[2]; #write new values to the datafile open(FILE, datafile.txt) or die (unable to open file.); print FILE ($a~); print FILE ($b~); print FILE ($c~); close(FILE); #end of problem section The above produces an empty datafile. I have tried to declare an explicit array for the file data using the following: open(FILE, datafile.txt) or die(Unable to open data file.); @values=FILE; close(FILE); foreach $element (@values) { ($a,$b,$c) = split(/~/, $element); $a = $a+$previousarray[0]; $b = $b+$previousarray[1]; $c = $c+$previousarray[2]; #then open the datafile and write new values. I keep getting use of unititialized values errors, and needs explicit package name errors, and an empty datafile. That's why I came to this forum for help. I also neglected to note in my original post that I need to access these new values elsewhere in the script. This specific action (open file, get data, perform math, write data) occurs in a subroutine in a much larger script, and I need to use these values in other subroutines in the script. But that's not the main problem yet. The main problem that prompted me to ask the question in the first place is getting this portion to work correctly so that I have the correct values in the datafile after these actions are performed. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: 1-line text file with numbers, need to add to them
For instance, the below is your data file --data.txt 12~s1~s314~s5677~s899~s0~s Here are the codes: #!/usr/bin/perl open(DATA,data.txt); while(DATA) { $number=$_; # print $number; while ($number =~ /([0-9]+)~s/g){ printf (%d\n,$1); } } close(DATA); On Feb 4, 7:27 am, cacogg...@gmail.com (Chris) wrote: I need some help with this problem. I've got a text file datafile with 1 line of data comprised of 30 different numbers delimited with ~s. I need to open this file, grab this line of data, split it into individual numbers, perform some simple math (addition) on each number, and then put the new values back into the datafile, replacing the original data that was there. I have tried for two days to figure out what I'm doing wrong, but I keep getting needs a package name errors for every variable nomenclature I try to work with. I've declare arrays and variables until my fingers are numb and nothing is working. I'm using Perl 5.008 if that matters. Can somebody please help? -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: 1-line text file with numbers, need to add to them
Hi Frank! On Thursday 04 Feb 2010 19:24:41 Frank wrote: For instance, the below is your data file --data.txt 12~s1~s314~s5677~s899~s0~s Here are the codes: #!/usr/bin/perl open(DATA,data.txt); while(DATA) { $number=$_; # print $number; while ($number =~ /([0-9]+)~s/g){ printf (%d\n,$1); } } close(DATA); This code snippet is wrong on so many levels: 1. No use strict; and no use warnings. 2. No three-args open , lexical filehandles and a trailing or die. Why did you post this to the list, possibly misleading other people, when you don't know the Modern Perl conventions? Regards, Shlomi Fish -- - Shlomi Fish http://www.shlomifish.org/ Interview with Ben Collins-Sussman - http://shlom.in/sussman Deletionists delete Wikipedia articles that they consider lame. Chuck Norris deletes deletionists whom he considers lame. Please reply to list if it's a mailing list post - http://shlom.in/reply . -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: 1-line datafile, need data for another routine
Chris Coggins wrote: I posted a question to this list yesterday from the google groups interface, asking for help with the following. I have since tried to post additional details in replies to that message using the google groups site and none of my posts have shown up on the list so let's try this again the right way. I have a datafile with 1 line of data, 30 numbers delimited by tildes. (Sample code below only uses 4 numbers to save time) I need to open this file, grab this line of data, split it into individual numbers, perform some simple math (addition) on each number, and then put the new values back into the datafile, replacing the original data that was there. I neglected to mention in my original post that I need to access these new values elsewhere in the script to perform additional math functions with them. I've tried several variations of the code below, including using arrays, and none of them got through without the script failing. The new datafile gets written, but it merely contains a ~. The errors I get are use of uninitialized values in such and such line and variables needs explicit package name. When the script does run, the variables lose their values as soon as I close the file after inhaling it, making all the rest of the actions in the subroutine futile. the datafile used below initially contains 30 values that were written previously, and this has been verified over and over. sub newValues { my($file) = shift; open(FILE, $file) or die(Unable to open data file.); while (FILE) { my($a,$b,$c,$d) = split(/~/, $_); $a = $a+$previousarray[4]; # I've tried to perform this math action after close(FILE) and get the same result - failure. $b = $b+$previousarray[7]; $c = $c+$previousarray[0]; } close(FILE); open(FILE, $file) || die (unable to open file); print FILE ($a~$b~$c \n); close(FILE); } #end sub Now my datafile just contains a single tilde and no values. I've also tried to bring the original data from the datafile into my(@array) and get the same errors. Keep in mind I need other subroutines to be able use these new values, but these local variables lose their values once the file is closed. I've also tried to declare them as global variables but I'm not doing something right because the script won't execute. I really need some help figuring this out if somebody would be kind enough to help a novice. Hello Chris Your lexical variables $a, $b, $c are local to the 'while' block, and do not exist outside it. Error Global symbol xx requires explicit package name is because the variable is not declared. Error Use of uninitialized value... is because Perl uses a value of 'undef' where variables are missing. As an aside it is bad form to use meaningless variable names, and $a and $b are special names that are used by core Perl so should be avoided. Also it is prefereable to use lexical file handles and the three-argument form of 'open', and incorporating the standard variable $! into the die string will give valuable information about why the operation failed. Declaring your variables outside the 'while' loop would fix your problem, but as you are interested only in the first line of the file it is as well to remove the loop altogether. Take a look at the code below and see if it meets your requirements. HTH, Rob sub newValues { my $file = shift; open my $data, '', $file or die Unable to open data file: $!; my $line = $data; close $data; my @data = split /~/, $line; die Invalid data format if @data 3; $data[0] += $previousarray[4]; $data[1] += $previousarray[7]; $data[2] += $previousarray[0]; open my $out, '', $file or die Unable to open output file: $!; print $out join('~', @data[0,1,2]), \n; close $out or die Failed to close output file: $!; } -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: 1-line datafile, need data for another routine
Hi Chris! On Friday 05 Feb 2010 11:56:49 Chris Coggins wrote: I posted a question to this list yesterday from the google groups interface, asking for help with the following. I have since tried to post additional details in replies to that message using the google groups site and none of my posts have shown up on the list so let's try this again the right way. I have a datafile with 1 line of data, 30 numbers delimited by tildes. (Sample code below only uses 4 numbers to save time) I need to open this file, grab this line of data, split it into individual numbers, perform some simple math (addition) on each number, and then put the new values back into the datafile, replacing the original data that was there. I neglected to mention in my original post that I need to access these new values elsewhere in the script to perform additional math functions with them. I've tried several variations of the code below, including using arrays, and none of them got through without the script failing. The new datafile gets written, but it merely contains a ~. The errors I get are use of uninitialized values in such and such line and variables needs explicit package name. When the script does run, the variables lose their values as soon as I close the file after inhaling it, making all the rest of the actions in the subroutine futile. the datafile used below initially contains 30 values that were written previously, and this has been verified over and over. Commenting on your code. Also, did you try using the Perl debugger (perl -d) to debug the code? sub newValues { my($file) = shift; 1. Your code needs indentation. 2. Either do: my $file = shift; Or: my ($file) = @_; Otherwise, it is confusing and the meaning may be lost. open(FILE, $file) or die(Unable to open data file.); 1. Don't use bareword filehandles - use lexicals. 2. Use three args open - open my $fh, , $file or die...; while (FILE) { Better do while (my $line = FILE) instead of relying on $_. my($a,$b,$c,$d) = split(/~/, $_); Don't call your lexical variables $a and $b - they are special built in variables. And you probably want an array here. $a = $a+$previousarray[4]; # I've tried to perform this math action after close(FILE) and get the same result - failure. $b = $b+$previousarray[7]; $c = $c+$previousarray[0]; You are updating the values of $a, $b, and $c, but they: 1. Will disappear after the loop has exited. 2. Won't be available after the loop's exit. } close(FILE); open(FILE, $file) || die (unable to open file); Again, see my remarks about open. print FILE ($a~$b~$c \n); Are you using strict and warnings? Regards, Shlomi Fish close(FILE); } #end sub Now my datafile just contains a single tilde and no values. I've also tried to bring the original data from the datafile into my(@array) and get the same errors. Keep in mind I need other subroutines to be able use these new values, but these local variables lose their values once the file is closed. I've also tried to declare them as global variables but I'm not doing something right because the script won't execute. I really need some help figuring this out if somebody would be kind enough to help a novice. -- - Shlomi Fish http://www.shlomifish.org/ First stop for Perl beginners - http://perl-begin.org/ Deletionists delete Wikipedia articles that they consider lame. Chuck Norris deletes deletionists whom he considers lame. Please reply to list if it's a mailing list post - http://shlom.in/reply . -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: 1-line text file with numbers, need to add to them
For instance, here is your data file. data.txt 12~s1~s314~s5677~s899~s0~s Then, here is the code. #!/usr/bin/perl open(DATA,data.txt); while(DATA) { $number=$_; # print $number; while ($number =~ /([0-9]+)~s/g){ printf (%d\n,$1); } } close(DATA); On Feb 4, 7:27 am, cacogg...@gmail.com (Chris) wrote: I need some help with this problem. I've got a text file datafile with 1 line of data comprised of 30 different numbers delimited with ~s. I need to open this file, grab this line of data, split it into individual numbers, perform some simple math (addition) on each number, and then put the new values back into the datafile, replacing the original data that was there. I have tried for two days to figure out what I'm doing wrong, but I keep getting needs a package name errors for every variable nomenclature I try to work with. I've declare arrays and variables until my fingers are numb and nothing is working. I'm using Perl 5.008 if that matters. Can somebody please help? -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: 1-line text file with numbers, need to add to them
On Feb 4, 2:27 am, cacogg...@gmail.com (Chris) wrote: I need some help with this problem. I've got a text file datafile with 1 line of data comprised of 30 different numbers delimited with ~s. I need to open this file, grab this line of data, split it into individual numbers, perform some simple math (addition) on each number, and then put the new values back into the datafile, replacing the original data that was there. I have tried for two days to figure out what I'm doing wrong, but I keep getting needs a package name errors for every variable nomenclature I try to work with. I've declare arrays and variables until my fingers are numb and nothing is working. I'm using Perl 5.008 if that matters. Can somebody please help? I posted a reply this morning in response to several messages here, and I included two different versions of the script I'm using that keeps failing. I posted my reply through the google groups interface but my post does not show up at the google site and it's been about 8 hours since posting. How long does it take for posts to show up if one uses the google interface because this delay is absurd? -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: 1-line text file with numbers, need to add to them
On Feb 4, 4:35 pm, jwkr...@shaw.ca (John W. Krahn) wrote: Chris wrote: I need some help with this problem. I've got a text file datafile with 1 line of data comprised of 30 different numbers delimited with ~s. I need to open this file, grab this line of data, split it into individual numbers, perform some simple math (addition) on each number, and then put the new values back into the datafile, replacing the original data that was there. perl -i.bak -pe's/(\d+)/ $1 + 3 /eg' yourdatafile John -- The programmer is fighting against the two most destructive forces in the universe: entropy and human stupidity. -- Damian Conway For instance, the below is your data file--- data.txt. 12~s1~s314~s5677~s899~s0~s Here is the codes: #!/usr/bin/perl open(DATA,data.txt); while(DATA) { $number=$_; # print $number; while ($number =~ /([0-9]+)~s/g){ printf (%d\n,$1); } } close(DATA); -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: 1-line text file with numbers, need to add to them
Frank wrote: On Feb 4, 4:35 pm, jwkr...@shaw.ca (John W. Krahn) wrote: Chris wrote: I need some help with this problem. I've got a text file datafile with 1 line of data comprised of 30 different numbers delimited with ~s. I need to open this file, grab this line of data, split it into individual numbers, perform some simple math (addition) on each number, and then put the new values back into the datafile, replacing the original data that was there. perl -i.bak -pe's/(\d+)/ $1 + 3 /eg' yourdatafile John -- The programmer is fighting against the two most destructive forces in the universe: entropy and human stupidity. -- Damian Conway Please don't quote sigs when you reply. For instance, the below is your data file--- data.txt. I'm sorry, I don't have a data file. 12~s1~s314~s5677~s899~s0~s Here is the codes: #!/usr/bin/perl You should include the warnings and strict pragmas so that perl can help you find mistakes: use warnings; use strict; open(DATA,data.txt); You should *always* verify that the file opened correctly before trying to use a possibly invalid filehandle: open FH, '', 'data.txt' or die Cannot open 'data.txt' $!; while(DATA) { $number=$_; That is usually written as: while ( my $number = FH ) { But why are you calling a line of input text number? # print $number; while ($number =~ /([0-9]+)~s/g){ printf (%d\n,$1); Why are you copying $1 to a string before having printf() convert it to a string? Why use printf() when print() would be better and simpler: print $1\n; } } close(DATA); John -- The programmer is fighting against the two most destructive forces in the universe: entropy and human stupidity. -- Damian Conway -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: 1-line text file with numbers, need to add to them
F == Frank caichao1...@gmail.com writes: F #!/usr/bin/perl F open(DATA,data.txt); F while(DATA) { F $number=$_; F # print $number; F while ($number =~ /([0-9]+)~s/g){ F printf (%d\n,$1); F } F } F close(DATA); regardless of the poor code there and others have commented on it, why did you post this three different times? and once using a different address. and please don't post code like that. it breaks many standard perl coding rules, and it doesn't even do anything close to what the OP wanted. uri -- Uri Guttman -- u...@stemsystems.com http://www.sysarch.com -- - Perl Code Review , Architecture, Development, Training, Support -- - Gourmet Hot Cocoa Mix http://bestfriendscocoa.com - -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: 1-line text file with numbers, need to add to them
cc == chaccou...@camcontacts com chaccou...@camcontacts.net writes: cc Please unsubscribe from chaccou...@camcontacts.com and h...@camcontacts.com i don't manage this list. you can follow the directions for subscribing which are in the headers of each email on the list. uri -- Uri Guttman -- u...@stemsystems.com http://www.sysarch.com -- - Perl Code Review , Architecture, Development, Training, Support -- - Gourmet Hot Cocoa Mix http://bestfriendscocoa.com - -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
multiple onchange on 1 cgi file
hi all, i'm newbie in perl.i have face problem how to add function ajax (onchange) on my file. this is my code... $ajx_ctrl = $query-param('ajx_ctrl'); $co_id = $query - param('select_co'); my $exported_fx = sub { my $searchterm = shift; my $sql = qq select file_name from file_name where id_module = ? ; my $dbh_label = $dbh_label; my $sth = $dbh_label-prepare( $sql ); $sth-execute( $searchterm . '%' ); my $html1 = ; $html1 = qq!select name=file_name id=id_module $input_style #OnChange=details( ['users'],['ddiv'] ); return true;\n!; my $firstrow = $sth-fetch(); if ( defined $firstrow ) { $html1 .= qq!option ! .qq!- Select One -! . qq!/option\n!; $html1.= qq!option! . $firstrow-[0] . qq!/option\n!; # dot on each option from the db while ( my $row = $sth-fetch() ) { $html1.= qq!option! . $row-[0] . qq!/option\n!; } } else {$html1 .= qq!option ! .qq!- Select One -! . qq!/option\n!;} # close off the select and return $html1 .= qq!/select\n!; #common_error($html1); return($html1); }; my $dbh_label = $dbh_label; $file_base .=qq~ select name=file_name $input_style option- Select One -/option /select ~; my $exported_form = sub { my $searchterm2 = shift; my $sql2 = qq select form_action from form where id_file = ? ; my $dbh_label = $dbh_label; my $sth2 = $dbh_label-prepare( $sql2 ); $sth2-execute( $searchterm2 . '%' ); my $html2 = ; $html2 = qq!select name=form_action id=id_file $input_style #OnChange=details( ['users'],['ddiv'] ); return true;\n!; my $firstrow2 = $sth2-fetch(); if ( defined $firstrow2 ) { $html2 .= qq!option ! .qq!- Select One -! . qq!/option\n!; $html2.= qq!option! . $firstrow2-[0] . qq!/option\n!; # dot on each option from the db while ( my $row = $sth2-fetch() ) { $html2.= qq!option! . $row-[0] . qq!/option\n!; } } else {$html2 .= qq!option ! .qq!- Select One -! . qq!/option\n!;} # close off the select and return $html2 .= qq!/select\n!; return($html2); }; my $dbh_label = $dbh_label; $form_base .=qq~ select name=form_name $input_style option- Select One -/option /select ~; #--- get module ---# $sql = qq~ SELECT id, module FROM module ~; $sth = $dbh_label-prepare($sql); $sth-execute() or common_error(SQL,Couldn't execute statement : $DBI::errstr,1); $sel_module .=qq~ option value=- Select One -/option ~; while (($id, $module) = $sth-fetchrow_array()) { $sel_module .=qq~ option value=$id $module/option ~; } $sth-finish(); #--# ### start add company form ## my $Show_Form = sub { my $html = ; $html .= EOT; HTML HEADtitleCGI::Ajax Example/title /HEAD BODY form action=setting_label_ajax.cgi method=post name=mainform input type=hidden value=Save name=action input type=hidden value=2 name=link tr height=20 td bgcolor=$table_colordiv name=co_level id=co_level $table_titlenbsp;b$forwhat/b/font/div/td /tr tr td width=729 div align=left !-- WE REPLACE THE HIDDEN TABLE ABOVE WITH THIS NEW ONE -- table width=100% border=1 cellpadding=0 cellspacing=0 style=border-collapse: collapse bordercolor=#11 id=AutoNumber21 tr td center table border=0 cellpadding=1 cellspacing=2 style=border- collapse: collapse bordercolor=#11 id=AutoNumber20 width=90% tr height=8td/td/tr tr height=25 td width=22%$content_styleModule/font/td td width=2%$content_style:/font/td td width=76% align=leftselect name=module id=module OnChange=search( ['module','NO_CACHE'],['ddiv'] ); return true; $input_style $sel_module /select /td /tr tr height=25 td$content_styleFile Name/font/td td$content_style:/font/td td div id=ddiv select name=file id=file_name OnChange=search2( ['file_name','NO_CACHE'],['ddiv'] ); return true; $input_style $file_base /select /div /td /tr tr height=25 td$content_styleForm/font/td td$content_style:/font/td td div id=ddiv $form_base /select /div /td /tr tr height=8td colspan=3/td/tr /table /td /tr /table
1-line text file with numbers, need to add to them
I need some help with this problem. I've got a text file datafile with 1 line of data comprised of 30 different numbers delimited with ~s. I need to open this file, grab this line of data, split it into individual numbers, perform some simple math (addition) on each number, and then put the new values back into the datafile, replacing the original data that was there. I have tried for two days to figure out what I'm doing wrong, but I keep getting needs a package name errors for every variable nomenclature I try to work with. I've declare arrays and variables until my fingers are numb and nothing is working. I'm using Perl 5.008 if that matters. Can somebody please help? -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: 1-line text file with numbers, need to add to them
Hi Chris! Have you visited http://perl-begin.org/ yet and read a good introductory book or tutorial? On Thursday 04 Feb 2010 09:27:32 Chris wrote: I need some help with this problem. I've got a text file datafile with 1 line of data comprised of 30 different numbers delimited with ~s. I need to open this file, grab this line of data, split it into individual numbers, perform some simple math (addition) on each number, and then put the new values back into the datafile, replacing the original data that was there. I have tried for two days to figure out what I'm doing wrong, but I keep getting needs a package name errors for every variable nomenclature I try to work with. I've declare arrays and variables until my fingers are numb and nothing is working. I'm using Perl 5.008 if that matters. You need to declare variables using my. Can you show us what you have so far? Regards, Shlomi Fish Can somebody please help? -- - Shlomi Fish http://www.shlomifish.org/ Why I Love Perl - http://shlom.in/joy-of-perl Deletionists delete Wikipedia articles that they consider lame. Chuck Norris deletes deletionists whom he considers lame. Please reply to list if it's a mailing list post - http://shlom.in/reply . -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: multiple onchange on 1 cgi file
On Thursday 04 Feb 2010 14:09:11 salmia wrote: hi all, i'm newbie in perl.i have face problem how to add function ajax (onchange) on my file. Hi salmia! Have you visited http://perl-begin.org/ yet and read a good introductory book or tutorial? Your code has many anti-patterns. this is my code... $ajx_ctrl = $query-param('ajx_ctrl'); $co_id= $query - param('select_co'); You should add use strict; and use warnings; at the top of your code, and fix all relevant errors and warnings. Also, please don't use too terse abbreviations like ajx instead of AJAX. I also think you should call $ajax_ctrl $ajax_control_value. my $exported_fx = sub { Why are you declaring a subroutine like that as a closure assigned to a my variable? A plain sub exported_fx { would be better. my $searchterm = shift; my $sql = qq select file_name from file_name where id_module = ? ; my $dbh_label = $dbh_label; What is the intention of the above line? my $sth = $dbh_label-prepare( $sql ); $sth-execute( $searchterm . '%' ); Do you realise that doing «id_module = mysearch%» in the SQL won't actually do a search? You need LIKE. And beware of SQL wildcards injection: http://phroggy.com/weblog/63.html Also it is customary to highlight the SQL keywords using ALL-CAPS. my $html1 = ; $html1 = qq!select name=file_name id=id_module $input_style #OnChange=details( ['users'],['ddiv'] ); return true;\n!; 1. Use here-documents for multi-line strings: http://www.shlomifish.org/lecture/Perl/Newbies/lecture4/string- forms/here_doc.html (short URL - http://xrl.us/bgukac ). 2. make sure $input_style does not have special HTML characters, or escape it. my $firstrow = $sth-fetch(); if ( defined $firstrow ) { $html1 .= qq!option ! .qq!- Select One -! . qq!/option\n!; 1. This should be one big string. 2. Please consider using a templating system such as: http://template-toolkit.org/ $html1.= qq!option! . $firstrow-[0] . qq!/option\n!; Now you have a potential cross-site scripting vulnerability here: http://en.wikipedia.org/wiki/Cross-site_scripting # dot on each option from the db while ( my $row = $sth-fetch() ) { $html1.= qq!option! . $row-[0] . qq!/option\n!; } } else {$html1 .= qq!option ! .qq!- Select One -! . qq!/option\n!;} # close off the select and return $html1 .= qq!/select\n!; #common_error($html1); Don't use ampersand-subroutine. return($html1); }; my $dbh_label = $dbh_label; Again - why? $file_base .=qq~ select name=file_name $input_style option- Select One -/option /select ~; use here-docs. my $exported_form = sub { my $searchterm2 = shift; my $sql2 = qq select form_action from form where id_file = ? ; my $dbh_label = $dbh_label; my $sth2 = $dbh_label-prepare( $sql2 ); $sth2-execute( $searchterm2 . '%' ); my $html2 = ; $html2 = qq!select name=form_action id=id_file $input_style #OnChange=details( ['users'],['ddiv'] ); return true;\n!; my $firstrow2 = $sth2-fetch(); if ( defined $firstrow2 ) { $html2 .= qq!option ! .qq!- Select One -! . qq!/option\n!; $html2.= qq!option! . $firstrow2-[0] . qq!/option\n!; # dot on each option from the db while ( my $row = $sth2-fetch() ) { Is there such a method of $sth called -fetch()? You should be more explicit - fetchrow_arrayref , etc. $html2.= qq!option! . $row-[0] . qq!/option\n!; } } else {$html2 .= qq!option ! .qq!- Select One -! . qq!/option\n!;} # close off the select and return $html2 .= qq!/select\n!; return($html2); }; This seems nearly identical to the previous function - please extract the common functionality to a subroutine. Regards my $dbh_label = $dbh_label; $form_base .=qq~ select name=form_name $input_style option- Select One -/option /select ~; #--- get module ---# $sql = qq~ SELECT id, module FROM module ~; $sth = $dbh_label-prepare($sql); $sth-execute() or common_error(SQL,Couldn't execute statement : $DBI::errstr,1); $sel_module .=qq~ option value=- Select One -/option ~; while (($id, $module) = $sth-fetchrow_array()) { $sel_module .=qq~ option value=$id $module/option ~; } $sth-finish(); #--# ### start add company form ## my $Show_Form = sub { my $html = ; Please use proper indentation inside of subroutines. $html .= EOT; Make sure here-docs are either «EOT» or «'EOT'» and not just EOT - see Perl Best Practices. Please fix all
Re: 1-line text file with numbers, need to add to them
Chris wrote: I need some help with this problem. I've got a text file datafile with 1 line of data comprised of 30 different numbers delimited with ~s. I need to open this file, grab this line of data, split it into individual numbers, perform some simple math (addition) on each number, and then put the new values back into the datafile, replacing the original data that was there. perl -i.bak -pe's/(\d+)/ $1 + 3 /eg' yourdatafile John -- The programmer is fighting against the two most destructive forces in the universe: entropy and human stupidity. -- Damian Conway -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Can't use string (1) as a HASH ref while strict refs in use at ./policy.sanitizer line 255.
Hi there, I am trying to figure out why the following lines are giving me an error: --- snip --- $found{filter}{$filter}{family}{$family} = 1; print keys %{ $found{filter}{$filter}{family} }; --- snip here's the error Can't use string (1) as a HASH ref while strict refs in use at ./policy.sanitizer line 255. I am trying to the display all the keys for $found{filter}{$filter}{family} please Cheers, Noah -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Can't use string (1) as a HASH ref while strict refs in use at ./policy.sanitizer line 255.
On 10/9/09 Fri Oct 9, 2009 2:12 PM, Noah noah-l...@enabled.com scribbled: Hi there, I am trying to figure out why the following lines are giving me an error: --- snip --- $found{filter}{$filter}{family}{$family} = 1; print keys %{ $found{filter}{$filter}{family} }; --- snip here's the error Can't use string (1) as a HASH ref while strict refs in use at ./policy.sanitizer line 255. I am trying to the display all the keys for $found{filter}{$filter}{family} please One of the values in your nested hash has the value 1 rather than a reference to a hash. Without seeing how you generated your hash it is impossible to say which element is in error. Use the Data::Dumper module to inspect nested hashes: use Data::Dumper; print Dumper(\%found); -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Can't use string (1) as a HASH ref while strict refs in use at ./policy.sanitizer line 255.
Noah wrote: Hi there, I am trying to figure out why the following lines are giving me an error: --- snip --- $found{filter}{$filter}{family}{$family} = 1; print keys %{ $found{filter}{$filter}{family} }; --- snip here's the error Can't use string (1) as a HASH ref while strict refs in use at ./policy.sanitizer line 255. I am trying to the display all the keys for $found{filter}{$filter}{family} please And which of those two lines in 255? Apparently, $found{filter}{$filter}{family} == 1 so this line: $found{filter}{$filter}{family}{$family} = 1; gives the error message. -- Just my 0.0002 million dollars worth, Shawn Programming is as much about organization and communication as it is about coding. I like Perl; it's the only language where you can bless your thingy. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: $| = 1 ???
2009/9/11 Raymond Wan r@aist.go.jp: Perldoc is somewhat hard to get into...but it's the manual for a programming language, so that's expected; I don't think having pages to color and draw on would be a feasible idea for the next update. :-) I don't think you should tar every perldoc page with the same brush. Different pages have different purposes. Some pages are reference manual material -- so that you can look stuff up and quickly get information on particular features. Reference manuals are great for experts to get information on specific things -- regex metacharacters, special variables, etc -- but terrible for learning from. Some pages are tutorial material -- to introduce you to a concept gently, one idea at a time, and with examples. These are great to learn from, but not so good for finding specific information. Both types of page are necessary, and in perldoc I have found that both do their job well. The only difficulty I can imagine with perldoc is that there isn't a clear enough delineation between the two categories, so a beginner might find a reference manual when what they need is a tutorial or vice versa. And #4, perldoc and anything like perldoc is competing with things like Google. Some people want to find the Perldoc pages; others might rather find a blog or a newsgroup posting discussing the problem -- everyone learns differently. If you want specific information, such as the purpose of $|, nothing beats a reference manual. Anything else will waste your time. If you want to learn about a topic, then tutorials, newsgroup discussions, blogs etc are the way to go. Phil -- I have always wished for my computer to be as easy to use as my telephone; my wish has come true because I can no longer figure out how to use my telephone. --Bjarne Stroustrup -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
$| = 1 ???
Hi, i can not understand, what does this code: $| = 1; Thanks
Re: $| = 1 ???
2009/9/10 Tariq Doukkali tariq.doukk...@autoform.de: Hi, i can not understand, what does this code: $| = 1; $| is a special variable. All perl special variables are listed in perldoc perlvar. See that document for a full explanation. Phil -- I have always wished for my computer to be as easy to use as my telephone; my wish has come true because I can no longer figure out how to use my telephone. --Bjarne Stroustrup -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: $| = 1 ???
TD == Tariq Doukkali tariq.doukk...@autoform.de writes: TD Hi, TD i can not understand, what does this code: TD $| = 1; all of perl's special variables are documented in perldoc perlvar. read that first and see if you learn what $| does. if you still don't get it, then ask here for clarification. uri -- Uri Guttman -- u...@stemsystems.com http://www.sysarch.com -- - Perl Code Review , Architecture, Development, Training, Support -- - Gourmet Hot Cocoa Mix http://bestfriendscocoa.com - -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: $| = 1 ???
On Thursday 10 September 2009 11:17:33 Tariq Doukkali wrote: Hi, i can not understand, what does this code: $| = 1; $| is a special variable. Reading its description from perldoc perlvar: $| If set to nonzero, forces a flush right away and after every write or print on the currently selected output channel. Default is 0 (regardless of whether the channel is really buffered by the system or not; $| tells you only whether you've asked Perl explicitly to flush after each write). STDOUT will typically be line buffered if output is to the terminal and block buffered otherwise. Setting this variable is useful primarily when you are outputting to a pipe or socket, such as when you are running a Perl program under rsh and want to see the output as it's happening. This has no effect on input buffering. See getc in perlfunc for that. See select in perldoc on how to select the output channel. See also IO::Handle. (Mnemonic: when you want your pipes to be piping hot.) What it means is that after you do it, then print will output everything immediately, without buffering it beforehand. Hope it helps, Shlomi Fish Thanks -- - Shlomi Fish http://www.shlomifish.org/ Optimising Code for Speed - http://shlom.in/optimise Chuck Norris read the entire English Wikipedia in 24 hours. Twice. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: $| = 1 ???
2009/9/10 Philip Potter philip.g.pot...@gmail.com: 2009/9/10 Tariq Doukkali tariq.doukk...@autoform.de: Hi, i can not understand, what does this code: $| = 1; This means the programmer wishes that the buffer will be flushed after every write, or print. Normally (i.e. $| = 0), the computer stores output in a buffer, which is processed, flushed, after its full. Since this might cause messages to not appear at due time (suffering from buffering), you may want, or need, to set the autoflush special variable ($|) to true (in Perl, you assign a true value, 1 in this case, to it). $| is a special variable. All perl special variables are listed in perldoc perlvar. See that document for a full explanation. This isn't really helping, sorry. -- Erez The government forgets that George Orwell's 1984 was a warning, and not a blueprint http://www.nonviolent-conflict.org/ -- http://www.whyweprotest.org/ -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: $| = 1 ???
ES == Erez Schatz moonb...@gmail.com writes: $| is a special variable. All perl special variables are listed in perldoc perlvar. See that document for a full explanation. ES This isn't really helping, sorry. sorry, but pointing someone to the docs is helping more than directly answering the question. this has been debated for years and teaching newbies how to use the docs has always proven to be a win because it is a skill they need to learn. perl's docs are among the best out there and very comprehensive. uri -- Uri Guttman -- u...@stemsystems.com http://www.sysarch.com -- - Perl Code Review , Architecture, Development, Training, Support -- - Gourmet Hot Cocoa Mix http://bestfriendscocoa.com - -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: $| = 1 ???
2009/9/10 Erez Schatz moonb...@gmail.com: 2009/9/10 Philip Potter philip.g.pot...@gmail.com: 2009/9/10 Tariq Doukkali tariq.doukk...@autoform.de: Hi, i can not understand, what does this code: $| = 1; This means the programmer wishes that the buffer will be flushed after every write, or print. Normally (i.e. $| = 0), the computer stores output in a buffer, which is processed, flushed, after its full. Since this might cause messages to not appear at due time (suffering from buffering), you may want, or need, to set the autoflush special variable ($|) to true (in Perl, you assign a true value, 1 in this case, to it). $| is a special variable. All perl special variables are listed in perldoc perlvar. See that document for a full explanation. This isn't really helping, sorry. I'll let the OP say whether he was helped by my answer or not. I prefer not to give a direct answer on-list which I can easily get from the docs. I don't mind if others prefer to give a direct answer on-list. But to leave off the most important piece of knowledge the beginner could take away from this -- how he could have looked it up for himself -- is being most unhelpful. You have solved his problem for today, but you have not helped him grow as a programmer. What if tomorrow he needs to know what $; means? With my answer, he now knows he can consult perldoc perlvar -- with yours, he is none the wiser and must return here. Philip -- I have always wished for my computer to be as easy to use as my telephone; my wish has come true because I can no longer figure out how to use my telephone. --Bjarne Stroustrup -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: $| = 1 ???
On Thu, Sep 10, 2009 at 10:26, Bryan R Harris bryan_r_har...@raytheon.com wrote: ES == Erez Schatz moonb...@gmail.com writes: $| is a special variable. All perl special variables are listed in perldoc perlvar. See that document for a full explanation. ES This isn't really helping, sorry. sorry, but pointing someone to the docs is helping more than directly answering the question. this has been debated for years and teaching newbies how to use the docs has always proven to be a win because it is a skill they need to learn. perl's docs are among the best out there and very comprehensive. Curiously the most helpful people on this list seem to think the perldoc system is great, but I've always found it to be rather hard to use. If I need to figure out what $. means, how do I even start? I can't type perldoc '$.' (well, I can, but it doesn't find anything). How would I ever know that perlvar is the place to go without asking? Everybody gets pointed back to the perldoc system, and yet when they have more questions, they often still have to come back here to even start. You start by saying [perldoc perl][1] which gives you an index of what is in the docs. You then say to yourself Self, what is $., you answer Why, it is a variable, self, you then look at the index and see that there is a whole document on variables (Look self, there is a whole document named [perlvar][2] that the index says contains information about 'Perl predefined variables', maybe it is there?). I am not saying the Perl documentation is perfect (I wouldn't be working on [perlopref][3] if I thought that), but is usable. Many people just aren't aware it is there. 1. http://perldoc.perl.org/perl.html 2. http://perldoc.perl.org/perlvar.html 3. http://github.com/cowens/perlopref -- Chas. Owens wonkden.net The most important skill a programmer can have is the ability to read. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: 2 files, 1 package, shared constants
Stanisław T. Findeisen schrieb: -BEGIN PGP SIGNED MESSAGE- Hash: SHA1 Hello there My application consists of several files. Some of them are to be run as CGI scripts, the others from command line. There is also a common file with constants and shared routines. The question is: what is the most standard way to export constants from that common file so that they could be used in the other files? The Exporter. package MyPackage; use warnings; use strict; use constant { ~MY_FIRST_CONSTANT = 'hello world!' }; *MY_SECOND_CONSTANT = [1, 3, 7]; *MY_SECOND_CONSTANT = \729; sub routine1 { ~print Hello from routine1! $MyPackage::MY_SECOND_CONSTANT\n; } This is scary, what is with the typegobs there? I would do something like this. package MyPackage; use warnings; use strict; use constant { MY_FIRST_CONSTANT = 'hello world!' }; use Exporter; our @EXPORT = qw/MY_FIRST_CONSTANT $MY_SECOND_CONSTANT routine1 /; #...@export_ok would be better our $MY_SECOND_CONSTANT = [1, 3, 7]; sub routine1 { print Hello from routine1! $MY_SECOND_CONSTANT\n; } == one.pl == use MyPackage; routine1(); print MY_FIRST_CONSTANT; print $MY_SECOND_CONSTANT; see perldoc Exporter -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: 2 files, 1 package, shared constants
Marc Lucksch wrote: Stanisław T. Findeisen schrieb: Subject: 2 files, 1 package, shared constants Hello there My application consists of several files. Some of them are to be run as CGI scripts, the others from command line. There is also a common file with constants and shared routines. The question is: what is the most standard way to export constants from that common file so that they could be used in the other files? The Exporter. That's probably true when you export symbols between packages. snip I would do something like this. package MyPackage; use warnings; use strict; use constant { MY_FIRST_CONSTANT = 'hello world!' }; use Exporter; our @EXPORT = qw/MY_FIRST_CONSTANT $MY_SECOND_CONSTANT routine1 /; #...@export_ok would be better In this case there is only one package. Would you still bother with Exporter? Why? -- Gunnar Hjalmarsson Email: http://www.gunnar.cc/cgi-bin/contact.pl -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
2 files, 1 package, shared constants
-BEGIN PGP SIGNED MESSAGE- Hash: SHA1 Hello there My application consists of several files. Some of them are to be run as CGI scripts, the others from command line. There is also a common file with constants and shared routines. The question is: what is the most standard way to export constants from that common file so that they could be used in the other files? Here is a minimal example: - one.pl package MyPackage; use warnings; use strict; use constant { ~MY_FIRST_CONSTANT = 'hello world!' }; *MY_SECOND_CONSTANT = [1, 3, 7]; *MY_SECOND_CONSTANT = \729; sub routine1 { ~print Hello from routine1! $MyPackage::MY_SECOND_CONSTANT\n; } # This is to satisfy require() 1; - two.pl package MyPackage; use warnings; use strict; require 'one.pl'; print 'The 1st constant is: ' . MyPackage-MY_FIRST_CONSTANT . \n; print 'The 2nd constant is: ' . *MY_SECOND_CONSTANT . \n; print ' SCALAR: ' . ${*MY_SECOND_CONSTANT{SCALAR}} . \n; print ' ARRAY: ' . join(', ', @{*MY_SECOND_CONSTANT{ARRAY}}) . \n; MyPackage-routine1; - This produces output like this: $ perl ./two.pl The 1st constant is: hello world! The 2nd constant is: *MyPackage::MY_SECOND_CONSTANT ~ SCALAR: 729 ~ ARRAY: 1, 3, 7 Hello from routine1! 729 Funny thing is that in two.pl MyPackage-MY_FIRST_CONSTANT works, but neither of these: print '' . MY_FIRST_CONSTANT . \n; print '' . MyPackage::MY_FIRST_CONSTANT . \n; Bareword MY_FIRST_CONSTANT not allowed while strict subs in use at ./two.pl line ***. Execution of ./two.pl aborted due to compilation errors. So I suspect that although I managed to solve the problem, the solution with MyPackage-MY_FIRST_CONSTANT is a bug in Perl or something?? Why should I be able to call the constant subroutine, but not be able to refer to the constant as is?? Why should I even bother with all these, since I am using only 1 package MyPackage? The documentation says package is namespace is symbol table. Why does MY_FIRST_CONSTANT work as is in one.pl, and not in two.pl? I am using Perl v5.8.8. STF === http://eisenbits.homelinux.net/~stf/ . My PGP key fingerprint is: 9D25 3D89 75F1 DF1D F434 25D7 E87F A1B9 B80F 8062 === -BEGIN PGP SIGNATURE- Version: GnuPG v1.4.7 (GNU/Linux) Comment: Using GnuPG with Fedora - http://enigmail.mozdev.org iD8DBQFJpSAQ6H+hubgPgGIRAoYHAJ4uRiGGwlAbjB3whHx8nDOZCN58QwCdHZTA Y7Anj2S1iXe93mES2d19REY= =iwf7 -END PGP SIGNATURE- -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: 2 files, 1 package, shared constants
Stanisław T. Findeisen wrote: snip Funny thing is that in two.pl MyPackage-MY_FIRST_CONSTANT works, but neither of these: print '' . MY_FIRST_CONSTANT . \n; print '' . MyPackage::MY_FIRST_CONSTANT . \n; Concatenation seems like a bad idea. Try: print MY_FIRST_CONSTANT, \n; print MyPackage::MY_FIRST_CONSTANT, \n; (untested) -- Gunnar Hjalmarsson Email: http://www.gunnar.cc/cgi-bin/contact.pl -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: 2 files, 1 package, shared constants
Gunnar Hjalmarsson wrote: Concatenation seems like a bad idea. Try: print MY_FIRST_CONSTANT, \n; print MyPackage::MY_FIRST_CONSTANT, \n; Ee... you mean . instead of , right? This: print MY_FIRST_CONSTANT . \n; print MyPackage::MY_FIRST_CONSTANT . \n; yields this output: MY_FIRST_CONSTANT MyPackage::MY_FIRST_CONSTANT which I would say is even more strange (but I am new to Perl). STF === http://eisenbits.homelinux.net/~stf/ . My PGP key fingerprint is: 9D25 3D89 75F1 DF1D F434 25D7 E87F A1B9 B80F 8062 === signature.asc Description: OpenPGP digital signature
Re: 2 files, 1 package, shared constants
Stanisław T. Findeisen wrote: Gunnar Hjalmarsson wrote: Concatenation seems like a bad idea. Try: print MY_FIRST_CONSTANT, \n; print MyPackage::MY_FIRST_CONSTANT, \n; Ee... you mean . instead of , right? No, I mean ,. You can print() a list. -- Gunnar Hjalmarsson Email: http://www.gunnar.cc/cgi-bin/contact.pl -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: 2 files, 1 package, shared constants
Stanisław T. Findeisen wrote: My application consists of several files. Some of them are to be run as CGI scripts, the others from command line. There is also a common file with constants and shared routines. First: Please disregard my theory about concatenation. Concatenation is ok, which is clearly stated in perldoc constant. The question is: what is the most standard way to export constants from that common file so that they could be used in the other files? Since the files share the same package, no exporting is needed. Here is a minimal example: - one.pl package MyPackage; use warnings; use strict; use constant { ~MY_FIRST_CONSTANT = 'hello world!' }; *MY_SECOND_CONSTANT = [1, 3, 7]; *MY_SECOND_CONSTANT = \729; sub routine1 { ~print Hello from routine1! $MyPackage::MY_SECOND_CONSTANT\n; } # This is to satisfy require() 1; - two.pl package MyPackage; use warnings; use strict; require 'one.pl'; print 'The 1st constant is: ' . MyPackage-MY_FIRST_CONSTANT . \n; print 'The 2nd constant is: ' . *MY_SECOND_CONSTANT . \n; print ' SCALAR: ' . ${*MY_SECOND_CONSTANT{SCALAR}} . \n; print ' ARRAY: ' . join(', ', @{*MY_SECOND_CONSTANT{ARRAY}}) . \n; MyPackage-routine1; I (now) believe that the problem is about compile time vs. runtime. When two.pl is compiled, one.pl has not yet been required. Two possible solutions: 1) Put the require statement in a BEGIN block. BEGIN { require 'one.pl' } 2) Convert one.pl to a module (one.pm) and use() it. use one; -- Gunnar Hjalmarsson Email: http://www.gunnar.cc/cgi-bin/contact.pl -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/