CGI: print $x =~ s/\n/<br>\n/g;

K

Ken Sington

In this test:

#!/usr/bin/perl -T
print "content-type: text/html \n\n";

use warnings;
use strict;

use CGI qw/param/;
my $x=param("x");

print qq{
<form method="GET">
<textarea name="x" cols="50" rows="20">$x</textarea><br>
<input type="submit">
</form>
};


print "<hr>\n";

my $s=length($x);
print $s;
print "<br>\n";

print $x =~ s/\n/<br>\n/g; #This one here...



=================


This: print $x =~ s/\n/<br>\n/g;

doesn't do this:
$x =~ s/\n/<br>\n/g;
print $x;
 
P

Paul Lalli

This: print $x =~ s/\n/<br>\n/g;

doesn't do this:
$x =~ s/\n/<br>\n/g;
print $x;


No, it doesn't. You're printing the return value of the substitution.
That is, you're printing the return value of the s/// operation. The
substitute operator returns the number of substitutions it made. It does
not return the new value of the binded variable.

Another way to illustrate:

$x = "123def789";
$num = ($x =~ s/[a-z]/#/g);
print "Substitutions: $num\n";
print "String: $x\n";

This prints 3 first, because the substitution happened three times (one
for each letter it replaced). It then prints the new string, '123###789'

Paul Lalli
 
G

gnari

Ken Sington said:
In this test:

[snip code that emits malformed html]
This: print $x =~ s/\n/<br>\n/g;

doesn't do this:
$x =~ s/\n/<br>\n/g;
print $x;

that's right. and what's more, this is true even
in a non-CGI situation.

the print prints the result of the s///g operation,
which is not the $x

gnari
 
J

J. Romano

Ken Sington said:
In this test:

This: print $x =~ s/\n/<br>\n/g;

doesn't do this:
$x =~ s/\n/<br>\n/g;
print $x;

You are correct. Your confusion probably comes from the fact that
the line:

print $x =~ s/\n/<br>\n/g;

looks like the line:

print $x = 5;

but behaves nothing like it.

When you say "$x = 5", the "=" operator changes the value of $x and
returns the same value (so it is the value of $x that gets printed
with the print() function). The "=~" operator, on the other hand,
changes the value of $x but does NOT return the value of $x.
According "perldoc perlop", it returns the number of substitutions
made (when used with s///), which is rarely what it sets $x to.

Therefore, the number of substitutions made is what gets passed to
the print() function, instead of the new value of $x, as you had
thought.

I hope this helps,

-- J.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top