Re: perlfaq4: expanding variables in strings

[email protected] (Robert Spier)
Newsgroups perl.perlfaq.workers
Message-ID <[email protected]>
Thanks for the patch, but I don't think it makes sense:

> After numerous heated debates on comp.lang.perl.* here is my new
> improved answer for perlfaq4: expanding variables in strings. 

I'm not sure it's "improved".

First, please adhere to the line wrapping used in the rest of the
document. 

> -See also ``How can I expand variables in text strings?'' in this
> +See also ``How can I expand/interpolate variables in text strings?'' in this
>  section of the FAQ.

I'm not sure the renaming makes sense.

> -=head2 How can I expand variables in text strings?
> -
> -Let's assume that you have a string like:
> +=head2 How can I expand/interpolate variables in text strings?

You've snipped the descriptive part.

> -    $text = 'this has a $foo in it and a $bar';
> +    $text = 'this has a $foo in it...\n  ...and a $bar';
> +    # Assume $text does not contain "\nEND\n" 
> +    chop ( $text = chop "<<END\n$text\nEND\n" );
> +    die if $@;

What are you trying to do here?

> -If those were both global variables, then this would
> -suffice:
> +This is dangerous if the text comes form an untrusted source,
> +consider:
>  
> -    $text =~ s/\$(\w+)/${$1}/g;  # no /e needed
> +    $text = '@{[ system "rm -rf /" ]}';

Why did you remove the simple and safe example of inserting global
variables?

Also, the system example is overly complicated to use in the FAQ
without explaining it.

> -But since they are probably lexicals, or at least, they could
> -be, you'd have to do this:
> +If you only need to process simple scalars then you can do limit the
> +parts of the string that are passed to eval() like this:
>  
>      $text =~ s/(\$\w+)/$1/eeg;
>      die if $@;			# needed /ee, not /e
>  
> -It's probably better in the general case to treat those
> -variables as entries in some special hash.  For example:
> +This still gives unrestricted access to your scalar variables.  It is
> +often better to use a hash:

I don't think this sentence is any clearer.

>  
>      %user_defs = ( 
>  	foo  => 23,
> @@ -924,8 +928,8 @@
>      );
>      $text =~ s/\$(\w+)/$user_defs{$1}/g;
>  
> -See also ``How do I expand function calls in a string?'' in this section
> -of the FAQ.
> +For other variations on the theme of text templates see the sprintf()
> +function and numerous modules on CPAN.

Why did you take out the reference?
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.