Re: substition in perl
- From: "Paul Lalli" <mritty@xxxxxxxxx>
- Date: 31 Mar 2006 11:01:18 -0800
dennisha...@xxxxxxxxx wrote:
Trying to figure out the substitution operator in Perl.
The documentation shows the syntax as
s/PATTERN/REPLALCEMENT/
and explains that the operator searches a string for PATTERN and
replaces that match with the REPLACEMENT text.
My question then is this. What string is being searched?
By default, the $_ variable. You can choose a different string,
however, by using the =~ (binding) operator, like so:
my $string = "hello world";
$string =~ s/hello/goodbye/;
print $string; # prints "goodbye world"
The
documention goes on to say that if no string is specified, the $_
variable is search.
What is the $_ variable?
$_ is the "default" variable for many many functions in Perl. It is
used as something of a shortcut, both for assigning to variables and
reading from variables. Some examples:
while (<$fh>) {
chomp;
s/hello/goodbye/;
my @fields = split /\t/;
foreach (@fields) {
my $len = length;
print;
}
}
Each one of these lines uses the $_ variable. The <$fh> (reading from
the $fh filehandle) as the sole condition to a while loop puts the line
it read into $_. chomp() removes the newlines from the end of $_.
s///, as you read above, searches-and-replaces on $_. split() splits
the string stored in $_. foreach puts each element of its list in $_
as it iterates over them. length() returns the length of $_ by
default. And print prints the contents of $_ by default.
We could re-write the above by explitily typing $_ everywhere that it's
implicitly used, and we'd get:
while ($_ = <$fh>) {
chomp $_;
$_ =~ s/hello/goodbye/;
my @fields = split (/\t/, $_);
foreach $_ (@fields) {
my $len = length($_);
print $_;
}
}
`perldoc perlvar` gives a complete list of all the places $_ is used
implicitly, by the way.
Hope this helps,
Paul Lalli
.
- References:
- substition in perl
- From: dennishancy
- substition in perl
- Prev by Date: Re: multi-line regular expression help
- Next by Date: Re: substition in perl
- Previous by thread: substition in perl
- Next by thread: Re: substition in perl
- Index(es):
Relevant Pages
|
|