Re: Using qr// with substitution and group-interpolation in thesubstitution part
On 10/25/23 10:32, Josef Wolf wrote: [...] Basically, I want to do the same as $data =~ s/^foo (whatever) bar$/bar $1 baz/mg; but with a different interface (because it has to be embedded into a bigger project), So I have come with this; sub substitute_lines { my ($contents, $regex, $subst) = @_; $contents =~ s/$regex/$subst/mg; return $contents; } } _lines ($data, qr/^foo (whatever) bar$/mg, 'bar $1 baz'); Which (mostly) works as expected. Unfortunately, this won't interpolate the matched group $1. [...] You could so something like: use feature qw(signatures); sub substitute_lines($contents, $regex, $subst) { $contents =~ s/$regex/$subst->()/emgr; } ... substitute_lines $data, qr/^foo (whatever) bar$/, sub { "bar $1 baz" }; This will pass an anonymous sub routine which will be called from s/// replacement side thanks to the /e modifier that allows code to be executed there. Also of some note is that the /r modifier is used so that s/// returns the resulting string instead of modifying $contents, and being the last statement, said resulting string is the return value. -- gordonfish -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Using qr// with substitution and group-interpolation in the substitution part
Hello, I tried to find a solution that doesn't use eval, although if '$1' is sent as a parameter to the subroutine as a simple string, I think it either need to be eval'ed or replaced literally. I made this solution to work with more capturing parans if necessary: use strict; use warnings; my $data = "foo whatever bar"; $data = substitute_lines( $data, qr/^foo (whatever) bar$/, 'bar $1 baz'); print "$data\n"; $data = "foo whatever bar whatever2 baz"; $data = substitute_lines( $data, qr/^foo (whatever) bar (whatever2) baz$/, 'bar $2 baz $1 foo'); print "$data\n"; sub substitute_lines { my ($contents, $regex, $subst) = @_; $contents =~ s/$regex(?{ $contents =~ s[$regex][$subst]gm; my @c = @{^CAPTURE}; $contents =~ s[\$$_][$c[$_-1]] for 1 .. @c })/$contents/; return $contents; } It prints: bar whatever baz bar whatever2 baz whatever foo However, the regex above uses code interpretation in regex, which is another kind of eval. So the following subroutine does the same thing with a simple replacement, without code interpretation: sub substitute_lines { my ($contents, $regex, $subst) = @_; $contents =~ s/$regex/$subst/gm; my @matches = @{^CAPTURE}; $contents =~ s/\$$_/$matches[$_-1]/g for 1 .. @matches; return $contents; } - Original Message - From: "Claude Brown via beginners" To: "Levi Elias Nystad-Johansen" ; "Andrew Solomon" Cc: "Josef Wolf" ; Sent: Thursday, October 26, 2023 12:07 AM Subject: RE: Using qr// with substitution and group-interpolation in the substitution part Josef, Inspired by Levi's “eval” idea, here is my solution: sub substitute_lines { my ($contents, $regex, $subst) = @_; eval "\$contents =~ s/$regex/$subst/g"; return $contents; } $data = "foo whatever bar"; $data = _lines($data, qr/^foo (whatever) bar$/m, 'bar $1 baz'); print "$data\n"; The differences: - escaped the "$" so the eval gets a literal "$contents" - didn't escape "$" so the eval receives the value of $regex and $subst - moved the "g" into the sub as it has no meaning for a qr// - removed the "m" from the sub as it best left with the original qr// - added "$data = ..." to get back the value from the subroutine Cheers, Claude. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
RE: Using qr// with substitution and group-interpolation in the substitution part
I should add that if the script reads values of $regex or $subst from an external source, then my use of eval is seriously flawed. For example, that external source might provide this value for $subst: /; system("do-bad-things"); qr/x/ The eval will execute the "do-bad-things" command on your system. -Original Message- From: Claude Brown via beginners Sent: Thursday, October 26, 2023 8:07 AM To: Levi Elias Nystad-Johansen ; Andrew Solomon Cc: Josef Wolf ; beginners@perl.org Subject: RE: Using qr// with substitution and group-interpolation in the substitution part CAUTION: This email originated from outside of the organization. Do not click links or open attachments unless you recognize the sender and know the content is safe. Josef, Inspired by Levi's “eval” idea, here is my solution: sub substitute_lines { my ($contents, $regex, $subst) = @_; eval "\$contents =~ s/$regex/$subst/g"; return $contents; } $data = "foo whatever bar"; $data = _lines($data, qr/^foo (whatever) bar$/m, 'bar $1 baz'); print "$data\n"; The differences: - escaped the "$" so the eval gets a literal "$contents" - didn't escape "$" so the eval receives the value of $regex and $subst - moved the "g" into the sub as it has no meaning for a qr// - removed the "m" from the sub as it best left with the original qr// - added "$data = ..." to get back the value from the subroutine Cheers, Claude.
RE: Using qr// with substitution and group-interpolation in the substitution part
Josef, Inspired by Levi's “eval” idea, here is my solution: sub substitute_lines { my ($contents, $regex, $subst) = @_; eval "\$contents =~ s/$regex/$subst/g"; return $contents; } $data = "foo whatever bar"; $data = _lines($data, qr/^foo (whatever) bar$/m, 'bar $1 baz'); print "$data\n"; The differences: - escaped the "$" so the eval gets a literal "$contents" - didn't escape "$" so the eval receives the value of $regex and $subst - moved the "g" into the sub as it has no meaning for a qr// - removed the "m" from the sub as it best left with the original qr// - added "$data = ..." to get back the value from the subroutine Cheers, Claude.
Re: Using qr// with substitution and group-interpolation in the substitution part
That's a fun question, Josef! I don't think you can pass a replacement phrase around, so this is all I came up with: sub substitute_lines { my ($contents, $subst) = @_; $contents = $subst->($contents); return $contents; } my $data = "foo whatever bar"; print(substitute_lines($data, sub { $_[0] =~ s/^foo (whatever) bar$/bar $1 baz/mgr } )); I'd be very pleased if someone could come up with a more elegant solution. On Wed, Oct 25, 2023 at 6:34 PM Josef Wolf wrote: > Hallo all, > > maybe this is not exactly a beginner question, but I could not find an > appropriate mailing list (all other lists seem to be developer realted). > > > Basically, I want to do the same as > > > $data =~ s/^foo (whatever) bar$/bar $1 baz/mg; > > > but with a different interface (because it has to be embedded into a bigger > project), So I have come with this; > > > sub substitute_lines { > my ($contents, $regex, $subst) = @_; > $contents =~ s/$regex/$subst/mg; > return $contents; > } > } > > _lines ($data, qr/^foo (whatever) bar$/mg, 'bar $1 baz'); > > > Which (mostly) works as expected. Unfortunately, this won't interpolate the > matched group $1. > > Experiments which also do not work: > > > _lines ($data, qr/^foo (whatever) bar$/mg, "bar $1 baz"); > # obviously, $1 is interpolated _before_ re-match is done > > > _lines ($data, qr/^foo (whatever) bar$/mge, '"bar $1 baz"'); > # /e modifier not accepted > > Any hints? > > -- > Josef Wolf > j...@raven.inka.de > > -- > To unsubscribe, e-mail: beginners-unsubscr...@perl.org > For additional commands, e-mail: beginners-h...@perl.org > http://learn.perl.org/ > > >
Using qr// with substitution and group-interpolation in the substitution part
Hallo all, maybe this is not exactly a beginner question, but I could not find an appropriate mailing list (all other lists seem to be developer realted). Basically, I want to do the same as $data =~ s/^foo (whatever) bar$/bar $1 baz/mg; but with a different interface (because it has to be embedded into a bigger project), So I have come with this; sub substitute_lines { my ($contents, $regex, $subst) = @_; $contents =~ s/$regex/$subst/mg; return $contents; } } _lines ($data, qr/^foo (whatever) bar$/mg, 'bar $1 baz'); Which (mostly) works as expected. Unfortunately, this won't interpolate the matched group $1. Experiments which also do not work: _lines ($data, qr/^foo (whatever) bar$/mg, "bar $1 baz"); # obviously, $1 is interpolated _before_ re-match is done _lines ($data, qr/^foo (whatever) bar$/mge, '"bar $1 baz"'); # /e modifier not accepted Any hints? -- Josef Wolf j...@raven.inka.de -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: interpolation without double quotes
On Thu, 5 Jul 2018 09:58:52 -0500 p...@reason.net wrote: > Many thanks to Shlomi and Uri: as always, you’ve greatly boosted my > understanding of Perl! — Rick > You're welcome. -- - Shlomi Fish http://www.shlomifish.org/ http://is.gd/htwEXQ - Integrating GNU Guile into GNU coreutils Mephiqoleth: THERE ARE JEWS OF MANY SPECIES. Selina: Really? That’s great - can I have a Jewish lady-cat? I want one so she can mother cute little Jewish kittens. — http://www.shlomifish.org/humour/Selina-Mandrake/ 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: interpolation without double quotes
Many thanks to Shlomi and Uri: as always, you’ve greatly boosted my understanding of Perl! — Rick > On Jul 4, 2018, at 9:35 AM, Shlomi Fish wrote: > > Hi Rick, > > On Wed, 4 Jul 2018 09:16:19 -0500 > Rick T wrote: > >> The following line works, even though I forgot to double quote the variable. >> >> my $student_directory = '/data/students/' . $student_id; >> > > see http://perl-begin.org/tutorials/bad-elements/#vars_in_quotes . Perl often > stringifies expressions even outside interpolation, such as when being > string-concatenated. > >> When I noticed this, I thought this was convenient: perl is trying to “do the >> right thing.” But I worry that leaving them out may be bad coding practice; >> if so, or you see other worthwhile improvements, please let me know. >> >> More importantly, I wonder how perl knows to do this. Perhaps context >> provided by the assignment operator or the concatenation operator? If there >> is a general rule on this, it would help me to know more widely when I can >> omit double quotes. >> >> Thanks! >> >> Rick Triplett > > > -- > - > Shlomi Fish http://www.shlomifish.org/ > First stop for Perl beginners - http://perl-begin.org/ > > After all is said and done, a hell of a lot more is said than done. >— Unclear source, via fortune-mod. > > 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/ > > > -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: interpolation without double quotes
Hi Rick, On Wed, 4 Jul 2018 09:16:19 -0500 Rick T wrote: > The following line works, even though I forgot to double quote the variable. > > my $student_directory = '/data/students/' . $student_id; > see http://perl-begin.org/tutorials/bad-elements/#vars_in_quotes . Perl often stringifies expressions even outside interpolation, such as when being string-concatenated. > When I noticed this, I thought this was convenient: perl is trying to “do the > right thing.” But I worry that leaving them out may be bad coding practice; > if so, or you see other worthwhile improvements, please let me know. > > More importantly, I wonder how perl knows to do this. Perhaps context > provided by the assignment operator or the concatenation operator? If there > is a general rule on this, it would help me to know more widely when I can > omit double quotes. > > Thanks! > > Rick Triplett -- - Shlomi Fish http://www.shlomifish.org/ First stop for Perl beginners - http://perl-begin.org/ After all is said and done, a hell of a lot more is said than done. — Unclear source, via fortune-mod. 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: interpolation without double quotes
On 07/04/2018 10:16 AM, Rick T wrote: The following line works, even though I forgot to double quote the variable. my $student_directory = '/data/students/' . $student_id; When I noticed this, I thought this was convenient: perl is trying to “do the right thing.” But I worry that leaving them out may be bad coding practice; if so, or you see other worthwhile improvements, please let me know. you don't need quotes on single scalar variables. in fact it is bad practice and can lead to bugs when you do that. what you did is not interpolation but ordinary concatenation with the . operator. interpolation is replacing scalars (and array) variables with their values inside double quotes. More importantly, I wonder how perl knows to do this. Perhaps context provided by the assignment operator or the concatenation operator? If there is a general rule on this, it would help me to know more widely when I can omit double quotes. the dot operator provides string context to both its arguments. if you are always double quoting single scalars, you should stop it as it is also slower due to the extra copying of the string value. that line is better written as: my $student_directory = "/data/students/$student_id"; i avoid using . when i can. it just reads better when you have the whole string in double quotes and you skip all the extra quote chars and . operators. uri
interpolation without double quotes
The following line works, even though I forgot to double quote the variable. my $student_directory = '/data/students/' . $student_id; When I noticed this, I thought this was convenient: perl is trying to “do the right thing.” But I worry that leaving them out may be bad coding practice; if so, or you see other worthwhile improvements, please let me know. More importantly, I wonder how perl knows to do this. Perhaps context provided by the assignment operator or the concatenation operator? If there is a general rule on this, it would help me to know more widely when I can omit double quotes. Thanks! Rick Triplett
Re: Interpolation Problem
To second what Uri mentioned already, On Fri, Jul 15, 2016 at 11:42 PM, AC Pwrote: > > > Argument "$command" isn't numeric in subtraction (-) at then it gives me > my directory. > > > This error message (I suspect it was a warning, can you check?) probably reported a line number. Could you post the code in the vicinity of that line number? (Better yet, post your whole script, or enough of a script to reproduce the problem.) Thanks! David -- "Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." -- Brian Kernighan
Re: Interpolation Problem
On 07/15/2016 11:42 PM, AC P wrote: Hello Perl gurus, I'm hoping someone here can provide a solution since I'm stuck. I'm trying to send TL1 commands resembling "RTRV-ALM-ALL;" (the simplest command you can send as an example here) via Net::SSH::Expect but they keep getting interpolated before even reaching the TL1 device. i think you misunderstand what interpolation means. in perl a scalar in a string is interpolated to its value. I predictably receive: Argument "$command" isn't numeric in subtraction (-) at then it gives me my directory. that feels like you are quoting $command and it is NOT being interpolated before it gets sent to the TL1. I think the solution lies in sending unicode e.g. chr(073) for ";" and chr(055) for "-" both of which are required to send the command and tell the TL1 device to process it. those aren't unicode chars (well they are but they are in the first 8 bit set so they are just ascii). why don't you post some of the code as it is hard to tell what you are actually doing wrong with just your conjectures. thanx, uri -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Interpolation Problem
Hello Perl gurus, I'm hoping someone here can provide a solution since I'm stuck. I'm trying to send TL1 commands resembling "RTRV-ALM-ALL;" (the simplest command you can send as an example here) via Net::SSH::Expect but they keep getting interpolated before even reaching the TL1 device. I predictably receive: Argument "$command" isn't numeric in subtraction (-) at then it gives me my directory. I think the solution lies in sending unicode e.g. chr(073) for ";" and chr(055) for "-" both of which are required to send the command and tell the TL1 device to process it. Suggestions, anyone? Amanda
interpolation problem in emacspipe.pl script from emacswiki
Dear List, i found on the emacswiki the following script written in Perl which is supposed to make emacsclient read from a pipe: #! /usr/bin/perl # This script uses emacsclient, be sure to have a running server session. # A server-session can be started by M-x server-start. my $status = system(emacsclient -n --eval '(progn (pop-to-buffer (get-buffer-create \*piped*\)))'); if($status!=0){ exit 1; } while(STDIN){ system(emacsclient -n --eval '(with-current-buffer \*piped*\ (insert \ . $_ . \))'); } Now when this script reads a list of emailaddresses for example from mutt: From: John Test john @test.org From: William Testtwo william test...@test.test.org it gives the following output: #buffer *piped* *ERROR*: Symbol's value as variable is void: William everything works normaly if before feeding the output to emacspipe.pl, i run it through sed s/\//g, whereby deleting the double quotes. There must be something about the interpolation. Maybe somebody has an idea? I am not an expert at this. Gabriel -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: interpolation problem in emacspipe.pl script from emacswiki
GS == Gabriel Striewe li...@gabriel-striewe.de writes: GS my $status = system(emacsclient -n --eval '(progn (pop-to-buffer (get-buffer-create \*piped*\)))'); GS if($status!=0){ exit 1; } GS while(STDIN){ GS system(emacsclient -n --eval '(with-current-buffer \*piped*\ (insert \ . $_ . \))'); GS } a first pass is for you to learn the qq{} alternate quote operator. escaping like you do is noisy and tricky. learn about these in perlop. qq{} is like but you can put inside without escaping. you can use any delimiter you like but paired {} is among the best (you can even have nested {} inside without escaping!). so those lines would look like (untested): my $status = system( qq{emacsclient -n --eval '(progn (pop-to-buffer (get-buffer-create *piped*)))' }); system( qq{ emacsclient -n --eval '(with-current-buffer *piped* (insert $_))' }); notice how much easier they are to read and you can see the are for emacs lisp and not for perl. actually i just noticed the first one doesn't to any perl interpolation so that could use q{} which is like ''. the second one needs double quotish behavior since it interpolates $_. another improvement would be to use a named variable in the while which makes the code easier to read. i stay away from $_ unless it is required or it has a major win. neither case applies here, so this is better. also you don't chomp the input line and that may also screw things up: while( my $email = STDIN ) { chomp $email ; system( qq{ emacsclient -n --eval '(with-current-buffer *piped* (insert $email))' }); } better formatting helps too. that code is now ready for you and others to understand easily and maintain. 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/
interpolation techniques (was Re: Here Docs)
t == trapd00r trapd...@trapd00r.se writes: i would say to just use a temporary scalar variable. there is no shame in doing this and it is simpler than using the Interpolation module which is doing tied things and calling eval (which is dangerous). t When I dont want to use a temp var, I usually do like this: t print EOF; t foo @{[scalar(localtime)]} bar t EOF t Do you approve? I do not see the benefit of using that Interpolation t module. that technique is old and not well liked by many. i never use it. it is just too noisy for my taste. also you can do a scalar version with ${\EXPR} but it also supplies a list context so there is little benefit over the array version. if you are just putting in a couple of elements then temp vars are fine and very clear. in a boston.pm thread on the same subject, the OP wrote his own version of the Interpolate module including the tied object and eval. that is just plain overkill. check out these methods i listed in that thread: ** first off there are the old hackish ways of doing this with dereferencing anon refs with code inside: text${\$foo-method()}more text t...@{[$foo-method()]}more text note that in both cases the method (or sub) is called in list context. this style is frowned upon for production code as it is noisy and not easy to read. an old reliable way is using sprintf as long as you don't have too many fields which again makes it noisy. sprintf text%smore text, $foo-method() ; if you want more templating without all the eval fuss and tied stuff, try my module Template::Simple. it would be very easy to use this for method interpolation: use Template::Simple ; my $tmpl = Template::Simple-new() ; my $out = render( text[%STUFF%]more text, { STUFF = $foo-method() } ) ; so no eval or tied is ever needed for basic stuff like interpolating methods and subs. three more ways i forgot to add. there is no shame or anything wrong with first putting the value of a method or sub call into a scalar and interpolating that. my $val = $foo-method() ; my $out = text${val}more text ; since you can interpolate hash values, a simple templater can be done this way: my %vals = ( FOO = $foo-method(), BAR = $bar-other_method ) ; my $out = text$vals{FOO}more text$vals{BAR} ; and the old way of using . is still fine even if i don't like it: my $out = text . $foo-method() . more text ; i just hate using . by itself. hard to read and rarely needed. note that i use .= a ton of times which is not the same. :) so that is 6 ways to do it without eval and tied. :) the point is choose a way to do it with the least work, least pain and most clarity for the reader of your code. the interpolate module (and copies) is dangerous because of its use of eval and slow (tied objects, tons of code to do something simple). 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/
Late interpolation of a scalar variable inside a string
I want to compute a file pathname based on a template at runtime, when I know the value of a variable that the template uses. In other words, the template for the path name looks like this... /foo/bar/$project/here ...and I want to evaluate this expression once I have set the value of $project. Here's what I've got: #!/usr/bin/perl use strict; use warnings; my $project = my-project; my $all_projects_path = '/foo/bar/$project/here'; my $project_path; my $temp = '$project_path = $all_projects_path'; print \$project is: $project\n; print \$all_projects_path is: $all_projects_path\n; print Evaluating: $temp\n; eval $temp; print \$project_path is now: $project_path\n; - Output: $ doit $project is: my-project $all_projects_path is: /foo/bar/$project/here Evaluating: $project_path = $all_projects_path $project_path is now: /foo/bar/$project/here - The variable $project wasn't interpolated. I've read perldoc on 'eval', and googled a bit, but no joy. I know this is going to be a forehead-slapper, but what have I done wrong? Thank, Chap -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Late interpolation of a scalar variable inside a string
On Sat, Mar 14, 2009 at 18:04, Chap Harrison c...@pobox.com wrote: I want to compute a file pathname based on a template at runtime, when I know the value of a variable that the template uses. In other words, the template for the path name looks like this... /foo/bar/$project/here snip I've read perldoc on 'eval', and googled a bit, but no joy. snip String eval is bad mojo. What you really need is either a template module* (if your needs are very complex) or a simple substitution (if you needs are simple). #!/usr/bin/perl use strict; use warnings; my $project_path_template = /foo/bar/{PROJECT}/here; for my $project (qw/project1 project2 project3/) { (my $project_path = $project_path_template) =~ s/\{PROJECT\}/$project/; print the project path is $project_path\n; } * Search CPAN for template modules until you find one with the features you want, this one looks fairly close to what you want: http://search.cpan.org/dist/Text-Template/lib/Text/Template.pm -- 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: Late interpolation of a scalar variable inside a string
Chap Harrison wrote: I want to compute a file pathname based on a template at runtime, when I know the value of a variable that the template uses. In other words, the template for the path name looks like this... /foo/bar/$project/here ...and I want to evaluate this expression once I have set the value of $project. Here's what I've got: #!/usr/bin/perl use strict; use warnings; my $project = my-project; my $all_projects_path = '/foo/bar/$project/here'; my $project_path; my $temp = '$project_path = $all_projects_path'; print \$project is: $project\n; print \$all_projects_path is: $all_projects_path\n; print Evaluating: $temp\n; eval $temp; print \$project_path is now: $project_path\n; - Output: $ doit $project is: my-project $all_projects_path is: /foo/bar/$project/here Evaluating: $project_path = $all_projects_path $project_path is now: /foo/bar/$project/here - The variable $project wasn't interpolated. I've read perldoc on 'eval', and googled a bit, but no joy. I know this is going to be a forehead-slapper, but what have I done wrong? Why not use sprintf() and '/foo/bar/%s/here' as the template: my $project = my-project; my $all_projects_path = '/foo/bar/%s/here'; my $project_path = sprintf $all_projects_path, $project; John -- Those people who think they know everything are a great annoyance to those of us who do.-- Isaac Asimov -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Late interpolation of a scalar variable inside a string
On Mar 14, 2009, at 5:24 PM, John W. Krahn wrote: Why not use sprintf() and '/foo/bar/%s/here' as the template: On Mar 14, 2009, at 5:19 PM, Chas. Owens wrote: * Search CPAN for template modules until you find one with the features you want, this one looks fairly close to what you want: http://search.cpan.org/dist/Text-Template/lib/Text/Template.pm Thank you both. Good to know about Template.pm. Also good to know the eval method was inadvisable. Since my needs are so simple, I went with the sprintf solution - simplest of all. Chap -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Stopping variable interpolation/evaluation
Use print(), not printf(). -- Gunnar Hjalmarsson Email:http://www.gunnar.cc/cgi-bin/contact.pl- Hide quoted text - - Show quoted text - Thanx Gunnar and Octavian, print() and chomp() together did the job just fine. ~Pushkar -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Stopping variable interpolation/evaluation
From: pushkar.n...@gmail.com Hi, I have a line read in perl from a file that itself is a source code for languages like c/sv etc. The variable containing this line contains special characters like %d. When i print this line to another file, the %d is evaluated and a 0 is getting printed. How do i overcome this and tell perl to strictly not interpolate/evaluate any contents of this variable and simply print it as is ! ~Pushkar open RFH File1.txt; Better use: open(my $rfh, , file1.txt) or die Can't read file1.txt - $!; open WFH File2.txt; Better use: open(my $wfh, , file2.txt) or die Can't write to file2.txt - $!; while ($line = RFH) Better use: while (my $line = $rfh) { chop($line); You might want to use: chomp $line; printf WFH $line\n; You might want to use: print $wfh $line\n; Octavian -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Stopping variable interpolation/evaluation
Hi, I have a line read in perl from a file that itself is a source code for languages like c/sv etc. The variable containing this line contains special characters like %d. When i print this line to another file, the %d is evaluated and a 0 is getting printed. How do i overcome this and tell perl to strictly not interpolate/evaluate any contents of this variable and simply print it as is ! ~Pushkar open RFH File1.txt; open WFH File2.txt; while ($line = RFH) { chop($line); printf WFH $line\n; } File1.txt : ovm_report_info(DBG_INFO, $psprintf(Programming Bank %d Reg %d, (i/ 32), l_uint_reg_num), OVM_HIGH); File2.txt ovm_report_info(DBG_INFO, $psprintf(Programming Bank 0 Reg 0, (i/ 32), l_uint_reg_num), OVM_HIGH); -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Stopping variable interpolation/evaluation
pushkar.n...@gmail.com wrote: Hi, I have a line read in perl from a file that itself is a source code for languages like c/sv etc. The variable containing this line contains special characters like %d. When i print this line to another file, the %d is evaluated and a 0 is getting printed. How do i overcome this and tell perl to strictly not interpolate/evaluate any contents of this variable and simply print it as is ! ~Pushkar open RFH File1.txt; open WFH File2.txt; while ($line = RFH) { chop($line); printf WFH $line\n; ^^ Use print(), not printf(). -- 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: interpolation of function reference in a here doc
On Jul 2, 9:27 am, [EMAIL PROTECTED] (Rob Dixon) wrote: Gabriel Striewe wrote: What do I do wrong? First of all, the ampersand subroutine designation is outdated and dangerous and it is far better to use the indirect notation for a subroutine call: $hello-() Perl will interpolate only simple variables or array or hash elements or slices. However we can cheat by putting the result of the call into an anonymous array and then dereferencing it: print END; hello @{[$hello-()]} END And don't worry too much about simply using a string: my $msg = $hello-(); print END; hello $msg END -- Brad -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/
Re: interpolation of function reference in a here doc
You may want to have a look at Interpolation.pm from CPAN. Jenda == [EMAIL PROTECTED] == http://Jenda.Krynicky.cz == : What do people think? What, do people think? :-) -- Larry Wall in [EMAIL PROTECTED] -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/
Re: interpolation of function reference in a here doc
On 7/2/07, Gabriel Striewe [EMAIL PROTECTED] wrote: Dear List, I wanted to interpolate a function reference in a here doc. The following works fine: my $hello = sub { return hello world!; }; printf hello $s\n, $hello(); But when I use a heredoc instead, it doesn't work: print END; hello $hello() END At least it does not properly dereference this function reference. What do I do wrong? You will encounter the problem if instead of printf hello %s\n, $hello(); you would have tried: print hello $hello()\n; That's an issue with the rules of string interpolation. (Read perldoc perlop, section on quote-like operators.) Simplistically, I think the right thing you are expecting for (calling the code ref in $hello) is not done because the only sigils that matter in interpolation are $ and @. That's why $ perl -e '$h = sub {1}; print hello $h() ' hello CODE(0x10240d64)() (where the only thing interpolated was the stringification of the code ref in $h). The weird/scary way to make it work is $ perl -e '$h = sub {1}; print hello @{[ $h() ]} ' hello 1 Thanks for your advice. Gabriel -- http://www.gabriel-striewe.de -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/
Re: interpolation of function reference in a here doc
On Jul 2, 2007, at 2:46 PM, Gabriel Striewe wrote: Dear List, I wanted to interpolate a function reference in a here doc. The following works fine: my $hello = sub { return hello world!; }; printf hello $s\n, $hello(); In Perl printf is rarely used because double-quote strings allow interpolation of scalars and arrays, and because print accepts an arbitrary number of arguments. Interpolation does not understand function calls, though, so you either use a multi-argument call like this: print hello , $hello-(), \n; or either use this hack: print hello @{[ $hello-() ]}\n; Here-documents have double-quote semantics unless you put single quotes around the terminating string, so that last trick works in here-documents as well. -- fxn -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/
Re: interpolation of function reference in a here doc
Gabriel Striewe wrote: I wanted to interpolate a function reference in a here doc. The following works fine: my $hello = sub { return hello world!; }; printf hello $s\n, $hello(); But when I use a heredoc instead, it doesn't work: print END; hello $hello() END At least it does not properly dereference this function reference. What do I do wrong? First of all, the ampersand subroutine designation is outdated and dangerous and it is far better to use the indirect notation for a subroutine call: $hello-() Perl will interpolate only simple variables or array or hash elements or slices. However we can cheat by putting the result of the call into an anonymous array and then dereferencing it: print END; hello @{[$hello-()]} END -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/
Re: Interpolation of backslash-escapes
Rob == Rob Dixon [EMAIL PROTECTED] writes: Can anybody think of an elegant solution? Rob eval qq($val); s/elegant/hacky, dangerous, broken/ Consider $val = ), $yourcode_here, (. -- Randal L. Schwartz - Stonehenge Consulting Services, Inc. - +1 503 777 0095 merlyn@stonehenge.com URL:http://www.stonehenge.com/merlyn/ Perl/Unix/security consulting, Technical writing, Comedy, etc. etc. See PerlTraining.Stonehenge.com for onsite and open-enrollment Perl training! -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Interpolation of backslash-escapes
Randal L. Schwartz wrote: Rob == Rob Dixon [EMAIL PROTECTED] writes: Can anybody think of an elegant solution? Rob eval qq($val); s/elegant/hacky, dangerous, broken/ Consider $val = ), $yourcode_here, (. Old news, out of context, petulant. Rob -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Interpolation of backslash-escapes
I am looking for an way to interpolate backslash-sequences within a string with the usual perl semantics, e.g. $s='1\t\2\t3\na\ b c' should become: '1tab2tab3 a b c' Things I tried were for example $s= eval('' . $val); # (hoping to trigger the normal interpolation) or $s=~ s/\\(.)/\\$1/eg; but somehow i couldn't get it right ... Can anybody think of an elegant solution? Regards, Peter Daum -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Interpolation of backslash-escapes
Peter Daum am Freitag, 3. November 2006 20:26: Hoi Peter, I am looking for an way to interpolate backslash-sequences within a string with the usual perl semantics, e.g. $s='1\t\2\t3\na\ b c' should become: '1tab2tab3 a b c' With usual perl semantics, the result is different :-) Things I tried were for example $s= eval('' . $val); # (hoping to trigger the normal interpolation) or $s=~ s/\\(.)/\\$1/eg; but somehow i couldn't get it right ... Can anybody think of an elegant solution? I think there are more elegant solutions, but in the following you have full control over what translates to what: #!/usr/bin/perl use strict; use warnings; my %trans=( '\t'=\t, '\n'=\n, '\ '=' ', '\2'='2', q(\\)=qw( \ ), # ;-) ); my $s='1\t\2\t3\na\ b c \\\ '; # last space: ;-) $s=~s; (\\.) ; $trans{$1} || $1 ;gex; print $s\n; # Note the usual perl semantics: print \2\ \n; __END__ Dani -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Interpolation of backslash-escapes
On 11/3/06, Peter Daum [EMAIL PROTECTED] wrote: I am looking for an way to interpolate backslash-sequences within a string with the usual perl semantics That's what eval does, although you have to build your string with care. Don't let the user put their own data into that string; they can (accidentally or intentionally) crash your program or worse, if you use eval. A better way would be to interpolate only the sequences that you need to support. I'd write a subroutine to do that, returning the converted string. It's simple to loop over the input string and build the new string as you go, and it completely avoids the riskiness of eval. Hope this helps! --Tom Phoenix Stonehenge Perl Training -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Interpolation of backslash-escapes
Peter Daum wrote: I am looking for an way to interpolate backslash-sequences within a string with the usual perl semantics, e.g. $s='1\t\2\t3\na\ b c' should become: '1tab2tab3 a b c' Things I tried were for example $s= eval('' . $val); # (hoping to trigger the normal interpolation) or $s=~ s/\\(.)/\\$1/eg; but somehow i couldn't get it right ... Can anybody think of an elegant solution? eval qq($val); But note that the \2 in your string (I don't know if it's a typo) will become a character with an octal value of 2, i.e. the ASCII STX control character. HTH, Rob -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Interpolation of backslash-escapes
Peter Daum wrote: I am looking for an way to interpolate backslash-sequences within a string with the usual perl semantics, e.g. $s='1\t\2\t3\na\ b c' should become: '1tab2tab3 a b c' Things I tried were for example $s= eval('' . $val); # (hoping to trigger the normal interpolation) or $s=~ s/\\(.)/\\$1/eg; but somehow i couldn't get it right ... Can anybody think of an elegant solution? $ perl -le' my %translate = ( t = \t, n = \n, r = \r, f = \f, b = \b, a = \a, e = \e, ); my $s = q[1\t\2\t3\na\ b c]; print $s; $s =~ s/\\(.)/ exists $translate{ $1 } ? $translate{ $1 } : $1 /seg; print $s; ' 1\t\2\t3\na\ b c 1 2 3 a b c John -- Perl isn't a toolbox, but a small machine shop where you can special-order certain sorts of tools at low cost and in short order. -- Larry Wall -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Interpolation of backslash-escapes
Rob Dixon wrote: Peter Daum wrote: I am looking for an way to interpolate backslash-sequences within a string with the usual perl semantics, e.g. $s='1\t\2\t3\na\ b c' should become: '1tab2tab3 a b c' Things I tried were for example $s= eval('' . $val); # (hoping to trigger the normal interpolation) or $s=~ s/\\(.)/\\$1/eg; but somehow i couldn't get it right ... Can anybody think of an elegant solution? eval qq($val); But note that the \2 in your string (I don't know if it's a typo) will become a character with an octal value of 2, i.e. the ASCII STX control character. I need to add that that solution relies on any parentheses in the string being in matching pairs. If you try $val = ')('; then it just won't work. If that's a problem, then you can use different delimiters, which are guaranteed to be either escaped or not in the string at all. The tilde is a useful one: eval qq~$val~; or if you're relaly stuck, then any character at all will do, including control characters: eval qq\0$val\0; works fine and delimits the string with null characters, Cheers, Rob -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
interpolation problems (was: Re: help in regular expression)
Irfan J Sayed schreef: #!/usr/local/bin/perl use warnings; use strict; Good! my $file = c:\backup.pl; Use my $file = 'c:\backup.pl'; or rather my $file = 'c:/backup.pl'; open(FH,$file) || die can't open a file; Make that: open my $fh, '', $file or die Error opening '$file': $! ; my $pattern = '\w\s\w'; my $pattern = qr/\w\s\w/ ; my $input = ; print yes got the match if $input =~ /$pattern/; Try this: while ( $fh ) { /$pattern/ and printf match in line %s\n, $. ; } but i am getting following error Name main::FH used only once: possible typo at C:\irfan\search.pl close $fh or die Error closing '$file': $! ; -- Affijn, Ruud Gewoon is een tijger. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: What is Variable Interpolation [was: Re: Help Required on the Script]
John W. Krahn am Freitag, 7. April 2006 01.09: D. Bolliger wrote: btw, @04 is not a valid (array) variable name; they must not start with a digit, as not keyword/builtin does. $ perl -Mwarnings -Mstrict -le' our @04 = 10 .. 14; print @04' 10 11 12 13 14 You are probably thinking scalars and/or lexicals. John, yes I did: $ perl -Mwarnings -Mstrict -le' my @04 = 10 .. 14; print @04' Can't use global @04 in my at -e line 1, near my @04 [...] Now I get the idea of the hint in the error I was (for a too short time) wondering about! Thanks! Dani -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
What is Variable Interpolation [was: Re: Help Required on the Script]
Mazhar am Donnerstag, 6. April 2006 11.48: thanks Raymond for the help it works, and what do u mean by variable interpolation Hello Mazhar It will help you a lot to know and use the documentation system of perl. You can get an overview by typing (on the command line): perldoc perl (docs) perldoc perldoc (documentation system) For your question with interpolatation, see perldoc perlop (and there Quote and Quote-like Operators and Regexp Quote-Like Operators) For builtin funtions (here, the example is q): perldoc -f q Some questions are answered by perldoc -q your question or some word(s) of the question The online docs can be found at http://www.perl.org/docs.html Variable interpolation is expanding variable values into a string, done by double quotes (or qq). Think about the following code (run in from command line): perl -le ' use strict; use warnings; my $word=q{Tip: }; my @words=qw/ look at the docs /; print q($word @words), \n; print qq($word @words\n); ' btw, @04 is not a valid (array) variable name; they must not start with a digit, as not keyword/builtin does. Other tips: When asking questions, - choose an apropriate subject line - snip away irrelevant parts of the post HTH! Dani -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: What is Variable Interpolation [was: Re: Help Required on the Script]
D. Bolliger wrote: btw, @04 is not a valid (array) variable name; they must not start with a digit, as not keyword/builtin does. $ perl -Mwarnings -Mstrict -le' our @04 = 10 .. 14; print @04' 10 11 12 13 14 You are probably thinking scalars and/or lexicals. John -- use Perl; program fulfillment -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: interpolation
John Doe wrote: The Ghost am Montag, 16. Januar 2006 06.34: I am storing text stings in a database. when I have the string: 'some perl $variable' which would print as: some perl $variable how can I force interpolation of '$variable'? one idea I thought of was: #!/usr/bin/perl my $var='variable'; $string='some $var'; $string=~s/\$(\w+)/${$1}/gi; print $string\n; But it doesn't work. I want it to print some variable. One way is to change the regex a bit: #!/usr/bin/perl use strict; use warnings; my $var='variable'; my $other_var='another'; my ($string1, $string2, $string3)=map 'some $var $other_var', 1..3; # test1, test2, final version: # $string1=~s/(\$\w+)/$1/g; $string2=~s/(\$\w+)/$1/ge; $string3=~s/(\$\w+)/$1/gee; print join \n, $string1, $string2, $string3; greetings joe Usually it is considered a bad idea to interpolate external strings. You could have your users printing any variable. Consider using sprintf instead (see `perldoc -f sprintf`). my $format = 'some perl %s'; my $string = sprintf $format, $variable; print $string\n; -- Just my 0.0002 million dollars worth, --- Shawn Probability is now one. Any problems that are left are your own. SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_ * Perl tutorials at http://perlmonks.org/?node=Tutorials * A searchable perldoc is available at http://perldoc.perl.org/ -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: interpolation
Shawn Corey am Montag, 16. Januar 2006 16.55: John Doe wrote: The Ghost am Montag, 16. Januar 2006 06.34: I am storing text stings in a database. when I have the string: 'some perl $variable' which would print as: some perl $variable how can I force interpolation of '$variable'? one idea I thought of was: #!/usr/bin/perl my $var='variable'; $string='some $var'; $string=~s/\$(\w+)/${$1}/gi; print $string\n; But it doesn't work. I want it to print some variable. One way is to change the regex a bit: #!/usr/bin/perl use strict; use warnings; my $var='variable'; my $other_var='another'; my ($string1, $string2, $string3)=map 'some $var $other_var', 1..3; # test1, test2, final version: # $string1=~s/(\$\w+)/$1/g; $string2=~s/(\$\w+)/$1/ge; $string3=~s/(\$\w+)/$1/gee; print join \n, $string1, $string2, $string3; greetings joe Usually it is considered a bad idea to interpolate external strings. You could have your users printing any variable. Consider using sprintf instead (see `perldoc -f sprintf`). my $format = 'some perl %s'; my $string = sprintf $format, $variable; print $string\n; As I understood The Ghost, the starting point string already contains a literal '$variable': 'some perl $variable'. I do not know the bigger picture of his problem, but I think an extensible way to replace a set of known names within a string by values would be (mirco templating system): === #!/usr/bin/perl use strict; use warnings; my %lookup=( var='variable', other_var='another', ); sub err {warn q(Unkown name '), shift, qq(' found\n)} my $string='some $var $other_var $unknown'; $string=~s { \$([a-zA-Z_]+) } { exists $lookup{$1} ? $lookup{$1} : do {err($1), ''} }gxe; print $string; === # prints: Unkown name 'unknown' found some variable another No interpolation involved, and the '$' sign preceding the names could be another one. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: interpolation
The Ghost am Freitag, 13. Januar 2006 21.23: I know I could do that, but what if I don't know the variable names in the string? $sql=~s/\$Status/$Status/; could I do: $sql=~s/\$(\S+)/${$1}/; On Jan 10, 2006, at 5:57 PM, John Doe wrote: The Ghost am Dienstag, 10. Januar 2006 21.57: I want to pull some text from a database: RxNumber in (select RxNumber FROM restoreReports WHERE Status in $Status) then I want perl to use this string and interpolate the variables ($Status). so: my $Status= ('New','Old'); my $sql=get_SQL_String(); #will get 'RxNumber in (select RxNumber FROM restoreReports WHERE Status in $Status)' $sql=~s/\$Status/$Status/; (first time as literal string, second time as perl variable defined in the surrounding context) see perldoc perlre print $sql; # should print: RxNumber in (select RxNumber FROM restoreReports WHERE Status in ('New','Old')) What can I do? Could you reformulate your (top posted) question? What do you mean exactly by not knowing the variable names in the string? - $Status (chars in the string) and/or - Status (mysql) and/or - $Status (in the perl code)? -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: interpolation
I am storing text stings in a database. when I have the string: 'some perl $variable' which would print as: some perl $variable how can I force interpolation of '$variable'? one idea I thought of was: #!/usr/bin/perl my $var='variable'; $string='some $var'; $string=~s/\$(\w+)/${$1}/gi; print $string\n; But it doesn't work. I want it to print some variable. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: interpolation
The Ghost am Montag, 16. Januar 2006 06.34: I am storing text stings in a database. when I have the string: 'some perl $variable' which would print as: some perl $variable how can I force interpolation of '$variable'? one idea I thought of was: #!/usr/bin/perl my $var='variable'; $string='some $var'; $string=~s/\$(\w+)/${$1}/gi; print $string\n; But it doesn't work. I want it to print some variable. One way is to change the regex a bit: #!/usr/bin/perl use strict; use warnings; my $var='variable'; my $other_var='another'; my ($string1, $string2, $string3)=map 'some $var $other_var', 1..3; # test1, test2, final version: # $string1=~s/(\$\w+)/$1/g; $string2=~s/(\$\w+)/$1/ge; $string3=~s/(\$\w+)/$1/gee; print join \n, $string1, $string2, $string3; greetings joe -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: interpolation
I know I could do that, but what if I don't know the variable names in the string? $sql=~s/\$Status/$Status/; could I do: $sql=~s/\$(\S+)/${$1}/; On Jan 10, 2006, at 5:57 PM, John Doe wrote: The Ghost am Dienstag, 10. Januar 2006 21.57: I want to pull some text from a database: RxNumber in (select RxNumber FROM restoreReports WHERE Status in $Status) then I want perl to use this string and interpolate the variables ($Status). so: my $Status= ('New','Old'); my $sql=get_SQL_String(); #will get 'RxNumber in (select RxNumber FROM restoreReports WHERE Status in $Status)' $sql=~s/\$Status/$Status/; (first time as literal string, second time as perl variable defined in the surrounding context) see perldoc perlre print $sql; # should print: RxNumber in (select RxNumber FROM restoreReports WHERE Status in ('New','Old')) What can I do? hth, joe -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
string interpolation when reading from a file
Greetings -- I am reading text sql commands) from a file, chopping it into sections and then writing each section out to a different file. Within the text are perl variables that I had expected to be interpolated as they were written out to the new file but they are not. Here is a sample line: REVOKE SELECT ON $TABLE_NAME FROM PUBLIC; $TABLE_NAME for example might be 'STUDENTS'. Is there a reason that the text is not being interpolated when before it is written out to the new file (either when it is read in or when it is printed out)? Here is a piece of my code: ##CODE SNIPPET # for $k ( @these_lines ) { # for debugging print $TABLE_NAME\n; print K\t=\t$k\n; ### SQL_OUT is the filehandle that I am writing to print SQL_OUT $k\n; } ### CLOSE-FOR-K produces this output in STDOUT: TABLE_NAME = STUDENTS K = REVOKE SELECT ON $TABLE_NAME FROM PUBLIC; where I want to have : K = REVOKE SELECT ON STUDENTS FROM PUBLIC; ##CODE SNIPPET # Thanks Dan -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
interpolation
I want to pull some text from a database: RxNumber in (select RxNumber FROM restoreReports WHERE Status in $Status) then I want perl to use this string and interpolate the variables ($Status). so: my $Status= ('New','Old'); my $sql=get_SQL_String(); #will get 'RxNumber in (select RxNumber FROM restoreReports WHERE Status in $Status)' something. print $sql; # should print: RxNumber in (select RxNumber FROM restoreReports WHERE Status in ('New','Old')) What can I do?
Re: interpolation
Try changing your $Status variable to this: my $Status = '(' . '' . join(',','New','Old') . '' . ')'; that should give the results desired hope it helps. The Ghost wrote: I want to pull some text from a database: RxNumber in (select RxNumber FROM restoreReports WHERE Status in $Status) then I want perl to use this string and interpolate the variables ($Status). so: my $Status= ('New','Old'); my $sql=get_SQL_String(); #will get 'RxNumber in (select RxNumber FROM restoreReports WHERE Status in $Status)' something. print $sql; # should print: RxNumber in (select RxNumber FROM restoreReports WHERE Status in ('New','Old')) What can I do? -- Mike(mickalo)Blezien =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= Thunder Rain Internet Publishing Providing Internet Solutions that work! http://thunder-rain.com/ =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: string interpolation when reading from a file
Dan Huston am Dienstag, 10. Januar 2006 21.40: Greetings -- I am reading text sql commands) from a file, chopping it into sections and then writing each section out to a different file. Within the text are perl variables that I had expected to be interpolated as they were written out to the new file but they are not. Here is a sample line: REVOKE SELECT ON $TABLE_NAME FROM PUBLIC; $TABLE_NAME for example might be 'STUDENTS'. Is there a reason that the text is not being interpolated when before it is written out to the new file (either when it is read in or when it is printed out)? Here is a piece of my code: ##CODE SNIPPET # for $k ( @these_lines ) { # for debugging print $TABLE_NAME\n; print K\t=\t$k\n; ### SQL_OUT is the filehandle that I am writing to print SQL_OUT $k\n; $k _itself_ is interpolated into the double quoted string: $k contains a string with content looking like perl vars, $k is replaced by this string. But there is - luckily! - no second level interpolation included (the variable names _in_ the string _in_ variable $k). You would have to make the second level interpolation explicit my $var='hi!'; print eval q(He said $var and disappeared); =He said hi! and disappeared but this is DANGEROUS since the text could contain code instead of simple variable names. There may be a useful templating module on search.cpan.org. Or you could reinvent the wheel and parse for the variable names and replace them with values. Something along the lines use strict; use warnings; my %vars=(TABLE_NAME='STUDENTS'); my @these_lines=('REVOKE SELECT ON $TABLE_NAME FROM PUBLIC $UNKNOWN;'); for (@these_lines) { s/\$([_a-zA-Z]\w*)/$vars{$1} || '$'.$1/eg; } print @these_lines; } ### CLOSE-FOR-K produces this output in STDOUT: TABLE_NAME = STUDENTS K = REVOKE SELECT ON $TABLE_NAME FROM PUBLIC; where I want to have : K = REVOKE SELECT ON STUDENTS FROM PUBLIC; ##CODE SNIPPET # Thanks Dan -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: interpolation
The Ghost am Dienstag, 10. Januar 2006 21.57: I want to pull some text from a database: RxNumber in (select RxNumber FROM restoreReports WHERE Status in $Status) then I want perl to use this string and interpolate the variables ($Status). so: my $Status= ('New','Old'); my $sql=get_SQL_String(); #will get 'RxNumber in (select RxNumber FROM restoreReports WHERE Status in $Status)' $sql=~s/\$Status/$Status/; (first time as literal string, second time as perl variable defined in the surrounding context) see perldoc perlre print $sql; # should print: RxNumber in (select RxNumber FROM restoreReports WHERE Status in ('New','Old')) What can I do? hth, joe -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Interpolation Problem with Matching
I am trying to compare files names listed in a file to the actual files in a directory. My code is as follows: Opendir(DIR,name); @files=readdir(DIR); Open(IN,fileList); While(IN) { If(/^pattern/) { moveFile($_); } } Close(IN); Sub moveFile() { My [EMAIL PROTECTED]; Foreach(@files) { If(/$src/) { Print $_\n; } } } I know this is not the most efficient, but I do not understand why the statement if(/$src/) is never true? Does not seem the $src is interpolated correctly for the match. Why is this happening? How can it be fixed? Thanks in advance!!! Jim
RE: Interpolation Problem with Matching
RICHARDS, JIM wrote: I am trying to compare files names listed in a file to the actual files in a directory. My code is as follows: Opendir(DIR,name); @files=readdir(DIR); Open(IN,fileList); While(IN) { If(/^pattern/) { moveFile($_); } } Close(IN); Sub moveFile() { My [EMAIL PROTECTED]; Foreach(@files) { If(/$src/) { Since you are using $src as the pattern, it will take any slashes it finds and take something like abc\g and look for abcg since a \ in pattern takes whatever the next character is. So even thouhg you see abc\g, the pattern is looking for abcg. Wrap the pattern in \Q$src\E which turns off any of the special characters. Wags ;) Print $_\n; } } } I know this is not the most efficient, but I do not understand why the statement if(/$src/) is never true? Does not seem the $src is interpolated correctly for the match. Why is this happening? How can it be fixed? Thanks in advance!!! Jim *** This message contains information that is confidential and proprietary to FedEx Freight or its affiliates. It is intended only for the recipient named and for the express purpose(s) described therein. Any other use is prohibited. *** -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Interpolation Problem with Matching
RICHARDS, JIM wrote: I am trying to compare files names listed in a file to the actual files in a directory. My code is as follows: Your code won't compile. Please add the following two lines: use warnings; use strict; to the top of your program and let perl help you find the mistakes. The best bet to solve your problem is to use a hash for the file names, something like: my $filelist = '/home/jim/filelist'; open FILES, '', $filelist or die Cannot open $filelist: $!; my %files; while ( FILES ) { chomp; $files{ $_ }++; } close FILES; my $dir = '/home/jim/somedir'; opendir DIR, $dir or die Cannot open $dir: $!; while ( my $file = readdir DIR ) { if ( exists $files{ $file } ) { print $file\n; } } closedir DIR; John -- use Perl; program fulfillment -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Variable interpolation inside an externa js file?
In my perl script I have put my javascript code in a separate file with the extension of js. I reference it with a javascript tag in the HTML. I have some code in there that is not in a procedure: it just executes prior to the body of the page loading as inline statements. Now I discover I need some of those URLs in my external javascript file to change depending on some perl parameters. This is not a procedure so I cannot just change some javascript procedure parameters. Perl does not process this file so it won't do the variable interpolation I want either. Below is the code that is causing the problem. I think the only way to resolve this is to cut the code below and move it to the perl code where I can use interpolation (which I would prefer not to do because it will really clutter up the main program -- oh well). Can anyone suggest a better approach? Thanks, Siegfried if (document.images) { one_on= new Image (); one_on.src= http://www.decisionchannel.com/breturn2.gif;; one_off = new Image(); one_off.src = http://www.decisionchannel.com/return2.gif;; two_on= new Image (); two_on.src= http://www.decisionchannel.com/f_bwhatbut2.gif;; two_off = new Image(); two_off.src = http://www.decisionchannel.com/f_whatbut2.gif;; ... // more of the same } -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Variable interpolation inside an externa js file?
On Mon, Nov 22, 2004 at 01:21:35PM -0700, Siegfried Heintze wrote: In my perl script I have put my javascript code in a separate file with the extension of js. I reference it with a javascript tag in the HTML. I have some code in there that is not in a procedure: it just executes prior to the body of the page loading as inline statements. Now I discover I need some of those URLs in my external javascript file to change depending on some perl parameters. This is not a procedure so I cannot just change some javascript procedure parameters. Perl does not process this file so it won't do the variable interpolation I want either. Below is the code that is causing the problem. I think the only way to resolve this is to cut the code below and move it to the perl code where I can use interpolation (which I would prefer not to do because it will really clutter up the main program -- oh well). Can anyone suggest a better approach? I'd suggest loading the js file using HTML::Template. Substitute the code you want with a TMPL_VAR /, and write some logic so that if the query string contains foo.js (a slight oversimplification) that it loads that template, prints it, then exits. Does that make sense to you? Anyone else? -- = Shaun Fryer = http://sourcery.ca/ ph: 416-544-9461 = -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Partial interpolation over pattern sustitution
How may I avoid partial interpolation over a pattern sustitution? My code looks like: # searching for all matches for later use @matches = $htmlpage =~ m/pre(.*?)\/pre/gs; for ($i=0; $i$#matches; $i++) { $htmlpage =~ s/pre$matches[$i]\/pre/predefined:$i\//; } The problem comes when the matches contains regex characters, and they try to be evaluated (ex. '|+--..' must be interpeted like '\|\+--\.\.'). Is the only solution implement a pre-transform regex characters? Any better (and fine) solution? TIA, -- Saludos, J. Alejandro Ceballos Z. | --+--- http://alejandro.ceballos.info | [EMAIL PROTECTED] | Estoy convencido ---+ de que en un principio tel: +52 (33) 3647-7809 | Dios hizo un mundo distinto cel: 044 (33) 1076-4705 | para cada hombre, + y que es en ese mundo, | que está dentro | de nosotros mismos, | donde deberíamos | intentar vivir. | | -- Oscar Wilde | -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
RE: Partial interpolation over pattern sustitution
J. Alejandro Ceballos Z. wrote: How may I avoid partial interpolation over a pattern sustitution? My code looks like: # searching for all matches for later use @matches = $htmlpage =~ m/pre(.*?)\/pre/gs; for ($i=0; $i$#matches; $i++) { $htmlpage =~ s/pre$matches[$i]\/pre/predefined:$i\//; } The problem comes when the matches contains regex characters, and they try to be evaluated (ex. '|+--..' must be interpeted like '\|\+--\.\.'). You can use the following prior to entering the for loop. $_ = quotemeta($_) for @matches; You could also combine the capturing and substitution something like this: my @matches; $htmlpage =~ s/pre(.*?)\/pre/push(@matches, $1) predefined:$#matches/geis; -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: second-level string interpolation
Michael C. Davis wrote: Hi, Apologies if I'm bringing up a repeated topic. I searched the list archive and the web and nothing specific has turned up so far. Is there a way to defer evaluation of the contents of a here-doc-defined value such that one can embed variables in the here-doc and not have them evaluated until they are used later? Something like this: It looks like you have gotten some good pointers to how you can accomplish this. I would suggest that you give some thought to whether it is a good idea to try this. What do you hope to accomplish by doing this? If you simply don't want to have the heredoc someplace where it interferes wh the flow of code, there is a much better, much less obfusciated way. code: - use strict; use warnings; my $header = 'end_of_header'; # File: $filename end_of_header my $filename = 'xyz'; print $header, \n; # output: want to see # File: xyz, but get # File: $filename I am not sure how the above is any more clear than it would be if you assigned a value to $filename first. I tried a few variations and nothing seems to work, as shown below. (This RFC http://dev.perl.org/perl6/rfc/229.html from Perl 6 implies that there is fact no way to do this.) Can anyone clarify. Thank you. How about this: Greetings! E:\d_drive\perlStuffperl -w use strict; use warnings; sub file_report_line { my $filename = shift; return END_STRING; # File: $filename END_STRING } my $filename = 'xyz'; print file_report_line($filename), \n ^Z # File: xyz Of course, the above code is rather senseless anyway, since it could be much more clearly written: return File: $filename; without all the baggage, but I am assuming that there is a bit more substance to your real heredoc. I still can't see a good reason for putting that low-level implementation detail at the top of the script, but this approach should work. Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: second-level string interpolation
At 10:39 AM 3/13/04 -0800, R. Joseph Newton wrote: my $header = 'end_of_header'; # File: $filename end_of_header my $filename = 'xyz'; print $header, \n; # output: want to see # File: xyz, but get # File: $filename I am not sure how the above is any more clear than it would be if you assigned a value to $filename first. Mainly that $filename would have different values at different times, in different code locations. I still can't see a good reason for putting that low-level implementation detail at the top of the script, but this approach should work. I agree, your approach is better at avoiding hidden dependencies and at keeping code and data closer together. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
second-level string interpolation
Hi, Apologies if I'm bringing up a repeated topic. I searched the list archive and the web and nothing specific has turned up so far. Is there a way to defer evaluation of the contents of a here-doc-defined value such that one can embed variables in the here-doc and not have them evaluated until they are used later? Something like this: code: - use strict; use warnings; my $header = 'end_of_header'; # File: $filename end_of_header my $filename = 'xyz'; print $header, \n; # output: want to see # File: xyz, but get # File: $filename I tried a few variations and nothing seems to work, as shown below. (This RFC http://dev.perl.org/perl6/rfc/229.html from Perl 6 implies that there is fact no way to do this.) Can anyone clarify. Thank you. code: - use strict; use warnings; my $header = 'end_of_header'; # File: $filename end_of_header my $filename = test; print $header, \n; print eval { $header }, \n; print $header, \n; print eval { $header }, \n; print ((eval $header) .\n); output [ .. editted for readability .. ]: --- # File: $filename # File: $filename # File: $filename # File: $filename Use of uninitialized value in concatenation (.) or string at ..\perlt\testevalsimple.pl line 15. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: second-level string interpolation
Michael C. Davis wrote: Is there a way to defer evaluation of the contents of a here-doc-defined value such that one can embed variables in the here-doc and not have them evaluated until they are used later? Something like this: code: - use strict; use warnings; my $header = 'end_of_header'; # File: $filename end_of_header my $filename = 'xyz'; print $header, \n; # output: want to see # File: xyz, but get # File: $filename I tried a few variations and nothing seems to work, as shown below. (This RFC http://dev.perl.org/perl6/rfc/229.html from Perl 6 implies that there is fact no way to do this.) Can anyone clarify. Thank you. i didn't check the link but from what you describe, i don't see any reason this can't be done: #!/usr/bin/perl -w use strict; my $s ='CODE'; I want to say: $v CODE my $v = 'hello world'; print eval qq.qq,$s,.; __END__ prints: I want to say: hello world david -- s$s*$+/tgmecJntgRtgjvqpCvuwL$;$;=qq$ \x24\x5f\x3d\x72\x65\x76\x65\x72\x73\x65 \x24\x5f\x3b\x73\x2f\x2e\x2f\x63\x68\x72 \x28\x6f\x72\x64\x28\x24\x26\x29\x2d\x32 \x29\x2f\x67\x65\x3b\x70\x72\x69\x6e\x74 \x22\x24\x5f\x5c\x6e\x22\x3b\x3b$;eval$; -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
RE: second-level string interpolation
Michael C. Davis wrote: Hi, Apologies if I'm bringing up a repeated topic. I searched the list archive and the web and nothing specific has turned up so far. Is there a way to defer evaluation of the contents of a here-doc-defined value such that one can embed variables in the here-doc and not have them evaluated until they are used later? Something like this: When you need to do something like that, I give them names like: myfilename Then do a $header =~ s/myfilename/$filename/gi; at the point you want to do the print. Now if doing more than once, then would wnat to put into secondardy variable to do the changes. code: - use strict; use warnings; my $header = 'end_of_header'; # File: $filename #File: myfilename end_of_header my $filename = 'xyz'; $header =~ s/myfilename/$filename/gi; print $header, \n; # output: want to see # File: xyz, but get # File: $filename The reason you are getting $filename in this instance has to do with using single ' vs double . If double had been used then you would have had: File: Wags ;) I tried a few variations and nothing seems to work, as shown below. (This RFC http://dev.perl.org/perl6/rfc/229.html from Perl 6 implies that there is fact no way to do this.) Can anyone clarify. Thank you. code: - use strict; use warnings; my $header = 'end_of_header'; # File: $filename end_of_header my $filename = test; print $header, \n; print eval { $header }, \n; print $header, \n; print eval { $header }, \n; print ((eval $header) .\n); output [ .. editted for readability .. ]: --- # File: $filename # File: $filename # File: $filename # File: $filename Use of uninitialized value in concatenation (.) or string at ..\perlt\testevalsimple.pl line 15. Any questions and/or problems, please let me know. Thanks. Wags ;) Int: 9-8-002-2224 Ext: 408-323-4225x2224 ** This message contains information that is confidential and proprietary to FedEx Freight or its affiliates. It is intended only for the recipient named and for the express purpose(s) described therein. Any other use is prohibited. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: second-level string interpolation
On 03/12/04 16:35, david wrote: Michael C. Davis wrote: Is there a way to defer evaluation of the contents of a here-doc-defined value such that one can embed variables in the here-doc and not have them evaluated until they are used later? Something like this: code: - use strict; use warnings; my $header = 'end_of_header'; # File: $filename end_of_header my $filename = 'xyz'; print $header, \n; # output: want to see # File: xyz, but get # File: $filename I tried a few variations and nothing seems to work, as shown below. (This RFC http://dev.perl.org/perl6/rfc/229.html from Perl 6 implies that there is fact no way to do this.) Can anyone clarify. Thank you. i didn't check the link but from what you describe, i don't see any reason this can't be done: #!/usr/bin/perl -w use strict; my $s ='CODE'; I want to say: $v CODE my $v = 'hello world'; print eval qq.qq,$s,.; __END__ prints: I want to say: hello world david To elaborate a bit, the reason for the failure is that while the string is interpolated, it is then also evaluated as perl code, so in my $header = 'end_of_header'; # File: $filename end_of_header my $filename = 'xyz'; print eval $header; the last statement ends up looking something like: print # File: xyz; which of course generates an error. The solution as David points out is to surround $header with double quotes. There are several ways to do this: $header = '' . $header . ''; # double quote the string in $header print eval $header; -or- print eval \$header\; -or- print eval qq($header); -or- print eval qq($header); etc. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: second-level string interpolation
Michael C. Davis wrote: Hi, Apologies if I'm bringing up a repeated topic. I searched the list archive and the web and nothing specific has turned up so far. Is there a way to defer evaluation of the contents of a here-doc-defined value such that one can embed variables in the here-doc and not have them evaluated until they are used later? Something like this: perldoc -q How can I expand variables in text strings John -- use Perl; program fulfillment -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: second-level string interpolation
On 03/12/04 16:08, Randy W. Sims wrote: To elaborate a bit, the reason for the failure is that while the string is interpolated, it is then also evaluated as perl code, so in my $header = 'end_of_header'; # File: $filename end_of_header my $filename = 'xyz'; print eval $header; the last statement ends up looking something like: print # File: xyz; I just realized that this might be a little misleading. If you break it down to: my $result = eval $header; print $result; You will get an uninitialized value error. What happens is that eval $header is first interpolated to eval { # File: xyz } which is executed as perl code. As perl code this is a comment and so produces no value, so $result ends up with no value, which is then printed in the next line, generating the uninitialized value error. Regards, Randy. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: second-level string interpolation
Randy W. Sims wrote: I just realized that this might be a little misleading. If you break it down to: my $result = eval $header; print $result; You will get an uninitialized value error. What happens is that eval $header is first interpolated to eval { # File: xyz } which is executed as perl code. As perl code this is a comment and so produces no value, so $result ends up with no value, which is then printed in the next line, generating the uninitialized value error. i think you have the right idea but your example is a little misleading, consider: [panda]# perl -W -le 'print eval #' [panda]# perl -W -le 'print eval {#}' # similiarly, now consider: [panda]# perl -W -le 'print eval undef' Use of uninitialized value in eval string at -e line 1. Use of uninitialized value in print at -e line 1. [panda]# perl -W -le 'print eval undef' Use of uninitialized value in print at -e line 1. [panda]# perl -W -le 'print eval {undef}' undef * we got 2 warnings for the first try because undef is evaluated once and then returned again to print * we got 1 warning because undef is returned from eval * we got no warnings for the last try because the string undef is returned from eval * eval{'#'} returns # not undef so your example above will not return undef * eval EXPR vs. eval BLOCK can be found at perldoc -f eval david -- s$s*$+/tgmecJntgRtgjvqpCvuwL$;$;=qq$ \x24\x5f\x3d\x72\x65\x76\x65\x72\x73\x65 \x24\x5f\x3b\x73\x2f\x2e\x2f\x63\x68\x72 \x28\x6f\x72\x64\x28\x24\x26\x29\x2d\x32 \x29\x2f\x67\x65\x3b\x70\x72\x69\x6e\x74 \x22\x24\x5f\x5c\x6e\x22\x3b\x3b$;eval$; -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: second-level string interpolation
Thanks everyone for the great ideas. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
OT: referencing, derefrencing, and interpolation WAS: using a CONSTANT as a pathname
Tassilo Von Parseval [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] On Sun, Jun 01, 2003 at 08:36:34PM -0400 Todd Wade wrote: Tassilo Von Parseval [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] On Sun, Jun 01, 2003 at 11:22:32AM +0200 Kevin Pfeiffer wrote: snip / open DATA, @{[ CFG ]} or die ...; The part between @{[ ]} is arbitry Perl-code that is executed in list context and the last expression evaluated in this Perl code is what gets eventually printed. After a little research, @{[ ... ]} will interpolate as the perl equivalent of: join($, @{[ ... ]}) and then return in the string. To get the behavior you describe above, one would use the code you provided below from the last post =0) note: [EMAIL PROTECTED] wadet]$ perl $ = '-'; print( time is: ${ \localtime }\n ); print( time is: @{ [localtime] }\n ); Ctrl-D time is: 1 time is: 13-24-6-2-5-103-1-152-1 If you want to interpolate a scalar value in a string you should probably avoid creating an array reference, if only to avoid confusion: [EMAIL PROTECTED] trwww]$ perl use constant A_CONSTANT = '/some/path'; print(the constant's value is: ${ \A_CONSTANT }\n); Ctrl-D the constant's value is: /some/path That's a bit better here because ${ \... } will execute the code in scalar-context instead of list-context. However, it wont always work as expected which is why I seldom use it. For instance: # this should work _theoretically_ print ${ \localtime }; # but doesn't: __END__ 1 This is the code that evaluates the expression and returns its last element to the \ operator, But only because the argument is a list, and not an array. Ive done a s/expected/defined/g on the way I code and things started working better for me =0) Im clarifying my thoughts and not yours... Im still a bit unsure, but I have to get to work now. Todd W. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]
RE: Best way to stop array interpolation.
Bakken, Luke wrote: Here's a quickie: I need to create a hash index out of a string that looks like this: loans:a_foo[0] If I build the index like this: $rec-{loans:a_$fld[$i]} = $tmp{$fld} || ''; perl thinks that $fld[$i] is an array element, which it isn't. Here are two solutions I found: $rec-{loans:a_$fld . [$i]} = $tmp{$fld} || ''; $rec-{loans:a_$fld\[$i]} = $tmp{$fld} || ''; Are there any other ways? Just curious. loans:a_${fld}[$i] also works. I like your second version above best. $ perl -MO=Deparse,-q -e 'a_${fld}[$i]' 'a_' . $fld . '[' . $i . ']'; $ perl -MO=Deparse,-q -e 'a_$fld\[$i]' 'a_' . $fld . '[' . $i . ']'; -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]
Best way to stop array interpolation.
Here's a quickie: I need to create a hash index out of a string that looks like this: loans:a_foo[0] If I build the index like this: $rec-{loans:a_$fld[$i]} = $tmp{$fld} || ''; perl thinks that $fld[$i] is an array element, which it isn't. Here are two solutions I found: $rec-{loans:a_$fld . [$i]} = $tmp{$fld} || ''; $rec-{loans:a_$fld\[$i]} = $tmp{$fld} || ''; Are there any other ways? Just curious. Luke -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]
RE: Best way to stop array interpolation.
Here are two solutions I found: $rec-{loans:a_$fld . [$i]} = $tmp{$fld} || ''; $rec-{loans:a_$fld\[$i]} = $tmp{$fld} || ''; Are there any other ways? Just curious. loans:a_${fld}[$i] also works. I like your second version above best. $ perl -MO=Deparse,-q -e 'a_${fld}[$i]' 'a_' . $fld . '[' . $i . ']'; $ perl -MO=Deparse,-q -e 'a_$fld\[$i]' 'a_' . $fld . '[' . $i . ']'; Hmm you know that was the first thing I tried, but I always get this error, indicating it's still looking for @fld: I also have use strict on. C:\tmpperl testadr Global symbol @fld requires explicit package name at testadr line 37. Global symbol @fld requires explicit package name at testadr line 43. BEGIN not safe after errors--compilation aborted at testadr line 48. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]
RE: Best way to stop array interpolation.
Bakken, Luke wrote: Here are two solutions I found: $rec-{loans:a_$fld . [$i]} = $tmp{$fld} || ''; $rec-{loans:a_$fld\[$i]} = $tmp{$fld} || ''; Are there any other ways? Just curious. loans:a_${fld}[$i] also works. I like your second version above best. $ perl -MO=Deparse,-q -e 'a_${fld}[$i]' 'a_' . $fld . '[' . $i . ']'; $ perl -MO=Deparse,-q -e 'a_$fld\[$i]' 'a_' . $fld . '[' . $i . ']'; Hmm you know that was the first thing I tried, but I always get this error, indicating it's still looking for @fld: I also have use strict on. C:\tmpperl testadr Global symbol @fld requires explicit package name at testadr line 37. Global symbol @fld requires explicit package name at testadr line 43. BEGIN not safe after errors--compilation aborted at testadr line 48. You're right. I guess what I wrote is a no-no. Writing something like ${fld}foo is like $fld . foo But the opening square bracket seems to cause problems with strict turned on. Maybe somebody smarter than me (shouldn't be hard to find!) can explain further. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]
Re: Help with Hash values and variable interpolation
112.58.26.32.32770 192.35.51.30.53: 64596[|domain] (DF) 112.58.26.32.32770 192.100.59.110.53: 24685 [1au][|domain] (DF) 112.58.26.4.2506 216.148.227.69.80: . ack 3280436924 win 2920 (DF) 112.58.26.4.2506 216.148.227.69.80: . ack 1759 win 1162 (DF) 112.58.26.4.2498 66.207.130.76.80: . ack 2195940947 win 7906 (DF) 112.58.26.4.2498 66.207.130.76.80: R 2576805184:2576805184(0) win 0 (DF) perl -ne '@a[/(\d+):/]++}{print Port 53: $a[53]\t Port 80: $a[80]\n' infile.txt Port 53: 2 Port 80: 4 -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]
Help with Hash values and variable interpolation
Hello all, I've got a file which contains ports and hostnames. I'd like to count the number of instances that each item occurs in my file. I'm having a difficult time with this. This is my script: Basically I'm splitting the first line a few times to get the data I need. What am I doing wrong? At the bottom you'll find a snippet of the file I'm parsing. Thank you for all your help! ### #/usr/bin/perl -w open (FILE,'c:\temp\outbound.traffic'); %allports=(); file=FILE; foreach (file) { chomp(); ($source,$other,$dest) = split(/\s/,$_); ($a,$b,$c,$d,$src_port)= split(/\./,$source); ($e,$f,$g,$h,$dst_port) = split(/\./,$dest); $sourceip = $a.$b.$c.$d; $destip = $e.$f.$g.$h; $dst_port =~ s/:/ /; push(dstports,$dst_port); }; foreach $element (dstports) { chomp($element); print $element\n; $allports{$element}++; } print Port 53: $allports{53}\t Port 80: $allports{80}\n; close (FILE); ###3 FILE THAT IS BEING PARSED 112.58.26.32.32770 192.35.51.30.53: 64596[|domain] (DF) 112.58.26.32.32770 192.100.59.110.53: 24685 [1au][|domain] (DF) 112.58.26.4.2506 216.148.227.69.80: . ack 3280436924 win 2920 (DF) 112.58.26.4.2506 216.148.227.69.80: . ack 1759 win 1162 (DF) 112.58.26.4.2498 66.207.130.76.80: . ack 2195940947 win 7906 (DF) 112.58.26.4.2498 66.207.130.76.80: R 2576805184:2576805184(0) win 0 (DF) == NOTICE - This communication may contain confidential and privileged information that is for the sole use of the intended recipient. Any viewing, copying or distribution of, or reliance on this message by unintended recipients is strictly prohibited. If you have received this message in error, please notify us immediately by replying to the message and deleting it from your computer. ==
RE: Help with Hash values and variable interpolation
I figured it out already! I ran a replace on the dst_port and replaced it with a whitespace which threw off the count. I've modified it to delete the whitespace and all works perfect. Joshua Scott Security Systems Analyst, CISSP 626-568-7024 -Original Message- From: Scott, Joshua [mailto:Joshua.Scott;Jacobs.com] Sent: Monday, November 04, 2002 5:42 PM To: '[EMAIL PROTECTED]' Subject: Help with Hash values and variable interpolation Hello all, I've got a file which contains ports and hostnames. I'd like to count the number of instances that each item occurs in my file. I'm having a difficult time with this. This is my script: Basically I'm splitting the first line a few times to get the data I need. What am I doing wrong? At the bottom you'll find a snippet of the file I'm parsing. Thank you for all your help! ### #/usr/bin/perl -w open (FILE,'c:\temp\outbound.traffic'); %allports=(); @file=FILE; foreach (@file) { chomp(); ($source,$other,$dest) = split(/\s/,$_); ($a,$b,$c,$d,$src_port)= split(/\./,$source); ($e,$f,$g,$h,$dst_port) = split(/\./,$dest); $sourceip = $a.$b.$c.$d; $destip = $e.$f.$g.$h; $dst_port =~ s/:/ /; push(@dstports,$dst_port); }; foreach $element (@dstports) { chomp($element); print $element\n; $allports{$element}++; } print Port 53: $allports{53}\t Port 80: $allports{80}\n; close (FILE); ###3 FILE THAT IS BEING PARSED 112.58.26.32.32770 192.35.51.30.53: 64596[|domain] (DF) 112.58.26.32.32770 192.100.59.110.53: 24685 [1au][|domain] (DF) 112.58.26.4.2506 216.148.227.69.80: . ack 3280436924 win 2920 (DF) 112.58.26.4.2506 216.148.227.69.80: . ack 1759 win 1162 (DF) 112.58.26.4.2498 66.207.130.76.80: . ack 2195940947 win 7906 (DF) 112.58.26.4.2498 66.207.130.76.80: R 2576805184:2576805184(0) win 0 (DF) == NOTICE - This communication may contain confidential and privileged information that is for the sole use of the intended recipient. Any viewing, copying or distribution of, or reliance on this message by unintended recipients is strictly prohibited. If you have received this message in error, please notify us immediately by replying to the message and deleting it from your computer. == == NOTICE - This communication may contain confidential and privileged information that is for the sole use of the intended recipient. Any viewing, copying or distribution of, or reliance on this message by unintended recipients is strictly prohibited. If you have received this message in error, please notify us immediately by replying to the message and deleting it from your computer. == == NOTICE - This communication may contain confidential and privileged information that is for the sole use of the intended recipient. Any viewing, copying or distribution of, or reliance on this message by unintended recipients is strictly prohibited. If you have received this message in error, please notify us immediately by replying to the message and deleting it from your computer. == -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]
Re: Help with Hash values and variable interpolation
Joshua Scott wrote: Hello all, Hello, I've got a file which contains ports and hostnames. I'd like to count the number of instances that each item occurs in my file. I'm having a difficult time with this. This is my script: Basically I'm splitting the first line a few times to get the data I need. What am I doing wrong? At the bottom you'll find a snippet of the file I'm parsing. Thank you for all your help! ### #/usr/bin/perl -w open (FILE,'c:\temp\outbound.traffic'); You should _always_ verify that the file opened successfully. Also, you can use slashes instead of backslashes in file names. open FILE, 'c:/temp/outbound.traffic' or die Cannot open 'c:/temp/outbound.traffic': $!; %allports=(); @file=FILE; foreach (@file) { You shouldn't read the whole file into an array unless you _really_ need to. while ( FILE ) { chomp(); You don't really need to chomp as you are not using the data at the end of the line. ($source,$other,$dest) = split(/\s/,$_); ($a,$b,$c,$d,$src_port)= split(/\./,$source); ($e,$f,$g,$h,$dst_port) = split(/\./,$dest); $sourceip = $a.$b.$c.$d; $destip = $e.$f.$g.$h; next unless my ( $source, $src_port, $dest, $dst_port ) = /^([\d.]+)\.(\d+)[ ]+([\d.]+)\.(\d+)/; $dst_port =~ s/:/ /; push(@dstports,$dst_port); print $dst_port\n; $allports{$dst_port}++; }; foreach $element (@dstports) { chomp($element); print $element\n; $allports{$element}++; } print Port 53: $allports{53}\t Port 80: $allports{80}\n; close (FILE); ###3 FILE THAT IS BEING PARSED 112.58.26.32.32770 192.35.51.30.53: 64596[|domain] (DF) 112.58.26.32.32770 192.100.59.110.53: 24685 [1au][|domain] (DF) 112.58.26.4.2506 216.148.227.69.80: . ack 3280436924 win 2920 (DF) 112.58.26.4.2506 216.148.227.69.80: . ack 1759 win 1162 (DF) 112.58.26.4.2498 66.207.130.76.80: . ack 2195940947 win 7906 (DF) 112.58.26.4.2498 66.207.130.76.80: R 2576805184:2576805184(0) win 0 (DF) John -- use Perl; program fulfillment -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]
Interpolation problem
Hi all - I can't figure this one out. I have a requirement to grab from some sort of input the elements of a regular expression and execute it. All is fine except when I use $1, $2, ... in the substitution, as: #!/usr/bin/perl use strict; use warnings; $_ = 'beau cox'; my $match = '(\w+)\s+(\w+)'; my $sub = '$2 $1'; s /$match/$sub/; print regex: s/$match/$sub/\nresult: $_\n\$1: $1\n\$2: $2\n; gives the output: regex: s/(\w+)\s+(\w+)/$2 $1/ result: $2 $1 $1: beau $2: cox I know the problem has something to do with my $2 $1 being inside $sub, but...? Aloha = Beau. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]
RE: Interpolation problem
You are using single quotes which tell Perl to NOT interpret what is between the single quotes. SO '$2 $1' becomes $2 $1 in the new variable while $2 $1 would become the values of $2 and $1. Wags ;) -Original Message- From: Beau E. Cox [mailto:[EMAIL PROTECTED]] Sent: Wednesday, August 28, 2002 11:07 To: [EMAIL PROTECTED] Subject: Interpolation problem Hi all - I can't figure this one out. I have a requirement to grab from some sort of input the elements of a regular expression and execute it. All is fine except when I use $1, $2, ... in the substitution, as: #!/usr/bin/perl use strict; use warnings; $_ = 'beau cox'; my $match = '(\w+)\s+(\w+)'; my $sub = '$2 $1'; s /$match/$sub/; print regex: s/$match/$sub/\nresult: $_\n\$1: $1\n\$2: $2\n; gives the output: regex: s/(\w+)\s+(\w+)/$2 $1/ result: $2 $1 $1: beau $2: cox I know the problem has something to do with my $2 $1 being inside $sub, but...? Aloha = Beau. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]
Re: Interpolation problem
On Aug 28, Beau E. Cox said: I can't figure this one out. I have a requirement to grab from some sort of input the elements of a regular expression and execute it. All is fine except when I use $1, $2, ... in the substitution, as: This is in the FAQ, and one of the MOST commonly asked FAQs I've ever seen. perldoc -q expand How can I expand variables in text strings? [...] Long story short: $m = '(\w+)\s+(\w+)'; # should consider using qr/(\w+)\s+(\w+)/ instead $r = '$1 $2'; s/$m/$r/ee; -- Jeff japhy Pinyan [EMAIL PROTECTED] http://www.pobox.com/~japhy/ RPI Acacia brother #734 http://www.perlmonks.org/ http://www.cpan.org/ ** Look for Regular Expressions in Perl published by Manning, in 2002 ** stu what does y/// stand for? tenderpuss why, yansliterate of course. [ I'm looking for programming work. If you like my work, let me know. ] -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]
RE: Interpolation problem
Thanks Japhy and Wags - I figured it was simple. Aloha = Beau. -Original Message- From: Jeff 'japhy' Pinyan [mailto:[EMAIL PROTECTED]] Sent: Wednesday, August 28, 2002 8:18 AM To: Beau E. Cox Cc: [EMAIL PROTECTED] Subject: Re: Interpolation problem On Aug 28, Beau E. Cox said: I can't figure this one out. I have a requirement to grab from some sort of input the elements of a regular expression and execute it. All is fine except when I use $1, $2, ... in the substitution, as: This is in the FAQ, and one of the MOST commonly asked FAQs I've ever seen. perldoc -q expand How can I expand variables in text strings? [...] Long story short: $m = '(\w+)\s+(\w+)'; # should consider using qr/(\w+)\s+(\w+)/ instead $r = '$1 $2'; s/$m/$r/ee; -- Jeff japhy Pinyan [EMAIL PROTECTED] http://www.pobox.com/~japhy/ RPI Acacia brother #734 http://www.perlmonks.org/ http://www.cpan.org/ ** Look for Regular Expressions in Perl published by Manning, in 2002 ** stu what does y/// stand for? tenderpuss why, yansliterate of course. [ I'm looking for programming work. If you like my work, let me know. ] -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]
Pattern-Matching var - interpolation.
Hello, I have a very unfunny problem, on which i am working for hours. I need to find out if a string contains an other specified string. I want to use pattern-matching. I can´t get a match together which make this. Look at my examples, none of the Matchings using vars works. If I replaces the vars to normal strings it works like it should. I am using perl 5.6 on a aix 4.3.3. Thanks for help! cut # #!/usr/bin/perl -w my $hund= hund m-a-u-s katze k.a.t.z.e. maus xyz 1234; my $dings1 = hund; my $dings2 = m-a-u-s; my $dings3 = k.a.t.z.e.; my $dings4 = xyz; my $dings5 = 123; if ( $dings1 =~ /\Q$hund/) { print $dings1 in \$hund;} if ( $dings1 =~ /\Q${hund}/) { print $dings1 in \$hund;} if ( $dings3 =~ /${hund}/) { print $dings3 in \$hund;} if ( $dings3 =~ /\Q${hund}/) { print $dings3 in \$hund;} if ( $dings5 =~ /$hund/) { print $dings5 in \$hund;} if ( $dings1 =~ /\Q$hund/) { print $dings1 in \$hund;} if ( $dings1 =~ /.*\Q${hund}\E.*/) { print $dings1 in \$hund;} if ( $dings3 =~ /\${hund}/) { print $dings3 in \$hund;} if ( $dings3 =~ /.*\Q${hund}/) { print $dings3 in \$hund;} if ( $dings5 =~ /.*$hund.*/) { print $dings5 in \$hund;} if ( $dings4 =~ /.*$hund.*/) { print $dings5 in \$hund;} ## EOF # -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]
Re: Pattern-Matching var - interpolation.
On Fri, 19 Jul 2002, Angerstein wrote: Hello, I have a very unfunny problem, on which i am working for hours. I need to find out if a string contains an other specified string. I want to use pattern-matching. I can´t get a match together which make this. Look at my examples, none of the Matchings using vars works. If I replaces the vars to normal strings it works like it should. I am using perl 5.6 on a aix 4.3.3. Thanks for help! cut # #!/usr/bin/perl -w my $hund= hund m-a-u-s katze k.a.t.z.e. maus xyz 1234; my $dings1 = hund; my $dings2 = m-a-u-s; my $dings3 = k.a.t.z.e.; my $dings4 = xyz; my $dings5 = 123; if ( $dings1 =~ /\Q$hund/) { print $dings1 in \$hund;} You are searching for $dings1 in $hund, this must be the other way around if ($hund =~ /\Q$hund/) You might also want to take a look at index (perldoc -f index). Note, if you are searching for 'orld' in 'Hello World' the regex will succeed. If you do not want this take look at '\b' in perldoc perlre if ( $dings1 =~ /\Q${hund}/) { print $dings1 in \$hund;} if ( $dings3 =~ /${hund}/) { print $dings3 in \$hund;} if ( $dings3 =~ /\Q${hund}/) { print $dings3 in \$hund;} if ( $dings5 =~ /$hund/) { print $dings5 in \$hund;} if ( $dings1 =~ /\Q$hund/) { print $dings1 in \$hund;} if ( $dings1 =~ /.*\Q${hund}\E.*/) { print $dings1 in \$hund;} if ( $dings3 =~ /\${hund}/) { print $dings3 in \$hund;} if ( $dings3 =~ /.*\Q${hund}/) { print $dings3 in \$hund;} if ( $dings5 =~ /.*$hund.*/) { print $dings5 in \$hund;} if ( $dings4 =~ /.*$hund.*/) { print $dings5 in \$hund;} ## EOF # -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]
Re: Pattern-Matching var - interpolation.
On Fri, 19 Jul 2002, Sudarshan Raghavan wrote: On Fri, 19 Jul 2002, Angerstein wrote: Hello, I have a very unfunny problem, on which i am working for hours. I need to find out if a string contains an other specified string. I want to use pattern-matching. I can´t get a match together which make this. Look at my examples, none of the Matchings using vars works. If I replaces the vars to normal strings it works like it should. I am using perl 5.6 on a aix 4.3.3. Thanks for help! cut # #!/usr/bin/perl -w my $hund= hund m-a-u-s katze k.a.t.z.e. maus xyz 1234; my $dings1 = hund; my $dings2 = m-a-u-s; my $dings3 = k.a.t.z.e.; my $dings4 = xyz; my $dings5 = 123; if ( $dings1 =~ /\Q$hund/) { print $dings1 in \$hund;} You are searching for $dings1 in $hund, this must be the other way around if ($hund =~ /\Q$hund/) sorry, this should be if ($hund =~ /\Q$dings1/) -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]
variable interpolation
Hi everyone, could somebody help me with the following problem: i have a code something like that my $variable = CGI-param('NAME'); #making connection to database . my $variable_ =$dbh-quote($variable); . $sth = -$dbh-prepare( SELECT something FROM some_table WHERE some_key=$variable_) then when I try to pass $variable_to a SQL statment the value of $variable_ was not passed so i can't fetch information fro the database. when i give the string to the SELECT statement directly every thing is fine, is working, that's why I consider that it is a problem of interpolation of the variable . could anybody help me Thanks, BD -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]
Re: variable interpolation
On Friday, April 19, 2002, at 07:18 AM, bernabe diaz wrote: Hi everyone, could somebody help me with the following problem: i have a code something like that my $variable = CGI-param('NAME'); #making connection to database . my $variable_ =$dbh-quote($variable); . $sth = -$dbh-prepare( SELECT something FROM some_table WHERE some_key= $variable_) i think you need to put single quotes around $variable_. $sth = -$dbh-prepare( SELECT something FROM some_table WHERE some_key= '$variable_' ); then when I try to pass $variable_to a SQL statment the value of $variable_ was not passed so i can't fetch information fro the database. when i give the string to the SELECT statement directly every thing is fine, is working, that's why I consider that it is a problem of interpolation of the variable . could anybody help me Thanks, BD -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]
variable interpolation
Thanks for help, but I tried that way too, and it does not work. BD bob ackerman wrote: On Friday, April 19, 2002, at 07:18 AM, bernabe diaz wrote: Hi everyone, could somebody help me with the following problem: i have a code something like that my $variable = CGI-param('NAME'); #making connection to database . my $variable_ =$dbh-quote($variable); . $sth = -$dbh-prepare( SELECT something FROM some_table WHERE some_key= $variable_) i think you need to put single quotes around $variable_. $sth = -$dbh-prepare( SELECT something FROM some_table WHERE some_key= '$variable_' ); then when I try to pass $variable_to a SQL statment the value of $variable_ was not passed so i can't fetch information fro the database. when i give the string to the SELECT statement directly every thing is fine, is working, that's why I consider that it is a problem of interpolation of the variable . could anybody help me Thanks, BD -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]
RE: variable interpolation
I prefer using a placeholder, you don't need to quote anything that way which avoids mistakes. my $sth = $dbh-prepare('SELECT something FROM some_table WHERE some_key = ?'); $sth-execute( CGI-param('NAME') ); Did you also print out the variable to prove that it does indeed contain some data? Do you also have the RaiseError attribute turned on to die if there are any SQL errors? Rob -Original Message- From: bernabe diaz [mailto:[EMAIL PROTECTED]] Subject: variable interpolation Thanks for help, but I tried that way too, and it does not work. BD bob ackerman wrote: On Friday, April 19, 2002, at 07:18 AM, bernabe diaz wrote: Hi everyone, could somebody help me with the following problem: i have a code something like that my $variable = CGI-param('NAME'); #making connection to database . my $variable_ =$dbh-quote($variable); . $sth = -$dbh-prepare( SELECT something FROM some_table WHERE some_key= $variable_) i think you need to put single quotes around $variable_. $sth = -$dbh-prepare( SELECT something FROM some_table WHERE some_key= '$variable_' ); snip -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]
RE: variable interpolation
-Original Message- From: bernabe diaz [mailto:[EMAIL PROTECTED]] Sent: Friday, April 19, 2002 10:18 AM To: [EMAIL PROTECTED] Subject: variable interpolation Hi everyone, could somebody help me with the following problem: i have a code something like that my $variable = CGI-param('NAME'); #making connection to database . my $variable_ =$dbh-quote($variable); . $sth = -$dbh-prepare( SELECT something FROM some_table WHERE ^^ This is a syntax error, no? some_key=$variable_) then when I try to pass $variable_to a SQL statment the value of $variable_ was not passed so i can't fetch information fro the database. when i give the string to the SELECT statement directly every thing is fine, is working, that's why I consider that it is a problem of interpolation of the variable . We can't see what the contents of $variable_ are, so we can't tell what the problem is. What *exactly* is being passed to the prepare() call? IOW, try something like this: my $sql = select * from foo where name=$variable_; print $sql, \n; my $sth = $dbh-prepare($sql) or die $DBI::errstr; -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]
Re: variable interpolation
Thank you very much !Now it's working! bd. Hanson, Robert wrote: I prefer using a placeholder, you don't need to quote anything that way which avoids mistakes. my $sth = $dbh-prepare('SELECT something FROM some_table WHERE some_key = ?'); $sth-execute( CGI-param('NAME') ); Did you also print out the variable to prove that it does indeed contain some data? Do you also have the RaiseError attribute turned on to die if there are any SQL errors? Rob -Original Message- From: bernabe diaz [mailto:[EMAIL PROTECTED]] Subject: variable interpolation Thanks for help, but I tried that way too, and it does not work. BD bob ackerman wrote: On Friday, April 19, 2002, at 07:18 AM, bernabe diaz wrote: Hi everyone, could somebody help me with the following problem: i have a code something like that my $variable = CGI-param('NAME'); #making connection to database . my $variable_ =$dbh-quote($variable); . $sth = -$dbh-prepare( SELECT something FROM some_table WHERE some_key= $variable_) i think you need to put single quotes around $variable_. $sth = -$dbh-prepare( SELECT something FROM some_table WHERE some_key= '$variable_' ); snip -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]
Variable Interpolation
Hi . Can you please help. When does Interpolation occur at Compile Time , Run Time or Both. So far I know on both, then why does the following not work. ( how can I get it to work ?) $scripts = 'cd $acu_home/bin \n nohup ${srv}_ss $srv.ini $acu_home/bin/$srv.out'; $acu_home = /luke/u01/app/rdf/product/4.1/acumate; $srv = edg; print(SCRIPT: $scripts \n); system($scripts); Thanks. Derek --Edcon Disclaimer - This email is private and confidential and its contents and attachments are the property of Edcon. It is solely for the named addressee. Any unauthorised use or interception of this email, or the review, retransmission, dissemination or other use of, or taking of any action in reliance upon the contents of this email, by persons or entities other than the intended recipient, is prohibited. Save for communications relating to the official business of Edcon, the company does not accept any responsibility for the contents of this email or any opinions expressed in this email or its attachments . If you are not the named addressee please notify us immediately by reply email and delete this email and any attached files. Due to the nature of email Edcon cannot ensure and accepts no liability for the integrity of this email and any attachments, nor that they are free of any virus. Edcon accepts no liability for any loss or damage whether direct or indirect or consequential, however caused, whether by negligence or otherwise, which may result directly or indirectly from this communication or any attached files. Edgars Consolidated Stores LTD ,Post office box 200 Crown Mines, Telephone: (011) 495-6000 -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]
Re: Question: Interpolation in Strings
From: G. E. [EMAIL PROTECTED] As I' ve read in Programming Perl, double-quoted strings are subject to variable interpolation of scalars and list values. Nothing else interpolates. So the following perl code won't compile: $st = !--- get_header(Users)---!; sub get_header{ $hnd-fixHead(@_); } use Interpolation get_header = sub { $hnd-fixHead(@_) }; $st = !--- $get_header{'Users'}---!; http://Jenda.Krynicky.cz/#Interpolation Jenda === [EMAIL PROTECTED] == http://Jenda.Krynicky.cz == There is a reason for living. There must be. I've seen it somewhere. It's just that in the mess on my table ... and in my brain. I can't find it. --- me -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]
Question: Interpolation in Strings
As I' ve read in Programming Perl, double-quoted strings are subject to variable interpolation of scalars and list values. Nothing else interpolates. So the following perl code won't compile: $st = !--- get_header(Users)---!; sub get_header{ $hnd-fixHead(@_); } also the following line of code won't compile (which does the same as the above): $st = !--- $hnd-fixHead(Users)---!; If I use the '.' operator (concatenation) my work is done. For example: $st = !--- . $hnd-fixHead(Users) . ---!; My question is if there is any way, that will let me do such an interpolation, without concatenation. For example I've started reading about overloading the stringify, but I realized that it isn't what I'm looking for. Is there a way to have the return value of $hnd-fixHead(Users) interpolated into my string, without concatenation? Thank you, Giannis -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]
Re: Question: Interpolation in Strings
G. E. wrote: As I' ve read in Programming Perl, double-quoted strings are subject to variable interpolation of scalars and list values. Nothing else interpolates. So the following perl code won't compile: $st = !--- get_header(Users)---!; sub get_header{ $hnd-fixHead(@_); } also the following line of code won't compile (which does the same as the above): $st = !--- $hnd-fixHead(Users)---!; If I use the '.' operator (concatenation) my work is done. For example: $st = !--- . $hnd-fixHead(Users) . ---!; My question is if there is any way, that will let me do such an interpolation, without concatenation. For example I've started reading about overloading the stringify, but I realized that it isn't what I'm looking for. Is there a way to have the return value of $hnd-fixHead(Users) interpolated into my string, without concatenation? perldoc -q 'How do I expand function calls in a string' John -- use Perl; program fulfillment -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]
Re: Question: Interpolation in Strings
On Feb 2, G. E. said: As I' ve read in Programming Perl, double-quoted strings are subject to variable interpolation of scalars and list values. Nothing else interpolates. So the following perl code won't compile: $st = !--- get_header(Users)---!; You have quotes inside of quotes. Try using different quotes, or using the q// or qq// operators: $st = !--- @{[ get_header('Users') ]} ---!; $st = qq(!--- @{[ get_header(Users) ]} ---!; For an explanation of how @{[ ... ]} works... 1. arrays DO get interpolated in strings 2. [ ... ] creates an array reference 3. @{ $array_ref } dereferences an array reference 4. @{[ ... ]} dereferences an array reference built on-the-fly 5. @{[ ... ]} expands that array as if it were @foo -- Jeff japhy Pinyan [EMAIL PROTECTED] http://www.pobox.com/~japhy/ RPI Acacia brother #734 http://www.perlmonks.org/ http://www.cpan.org/ ** Look for Regular Expressions in Perl published by Manning, in 2002 ** stu what does y/// stand for? tenderpuss why, yansliterate of course. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]
Re: Variable interpolation?
06/01/02 17:20:37, Jeff 'japhy' Pinyan [EMAIL PROTECTED] a écrit: The contents of @string are raw text. You'll need to expand the variables in it manually: perldoc -q 'expand variables' That FAQ will tell you what to do. Thanks, Jeff, for taking the time to answer. My problem was, as a beginner, that I didn't know where to start looking in the documentation, since I didn't know what the problem was :) -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]
Variable interpolation?
Hi everyone. A little thing I fail to understand... This of course works: $name=Dave; $string=Hello $name; print $string; outputting: Hello Dave Why, then, does it not work when I get the string Hello $name out of a file? $name=Dave; $in=textfile.txt; open(INFILE, $in); @string=INFILE; $string=$string[0]; print $string; The output is: Hello $name Thanks a million if anyone has the answer Dave Jones -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]
Re: Variable interpolation?
On Jan 6, Mad B.Jones said: $name=Dave; $in=textfile.txt; open(INFILE, $in); @string=INFILE; $string=$string[0]; The contents of @string are raw text. You'll need to expand the variables in it manually: perldoc -q 'expand variables' That FAQ will tell you what to do. -- Jeff japhy Pinyan [EMAIL PROTECTED] http://www.pobox.com/~japhy/ RPI Acacia brother #734 http://www.perlmonks.org/ http://www.cpan.org/ ** Look for Regular Expressions in Perl published by Manning, in 2002 ** stu what does y/// stand for? tenderpuss why, yansliterate of course. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]