#!/usr/bin/perl -w
use strict;
$\="\n";
## first, to BrowserUk's misunderstanding, an explanation
my $s = 'ABCD';
print substr($s,0,2)=''; # EXPECT 'CD', what's left
print $s; # CD
$s = 'ABCD';
print substr($s,0,2,''); # EXPECT 'AB',
print $s; # CD
# perldoc -f substr
# An alternative to using substr() as an lvalue is to specify the
# replacement string as the 4th argument. This allows you to
# replace parts of the EXPR and return what was there before in
# one operation, just as you can with splice().
my @B = 1..4;
print splice(@B,0,2,()); # expect 12
print @B; # expect 34
# perldoc -f splice
# Removes the elements designated by OFFSET and LENGTH from an
# array, and replaces them with the elements of LIST, if any. In
# list context, returns the elements removed from the array.
# now to tye's argument, saying that substr($s,0,2)= EXPR
# doesn't return EXPR and is therefore a bug
# perldoc -f substr
# You can use the substr() function as an lvalue, in which case
# EXPR must itself be an lvalue.
$s = '1234';
@B=();
$B[0] = substr($s,0,2) = 'ab';
print $s; # EXPECT ab34
print "@B"; # EXPECT ab
print "ASSIGN '' ";
$s = '1234';
@B=();
$B[0] = substr($s,0,2) = '';
print $s; # expect 34
print "@B"; # EXPECT 34, cause '' wouldn't be an lvalue
print "ASSIGN undef ";
$s = '1234';
@B=();
$B[0] = substr($s,0,2) = undef;
print $s; # expect 34
print "@B"; # EXPECT 34, cause undef wouldn't be an lvalue
## CONCLUSION
## if '' and undef are lvalues, then this is a feature, and not a bug
__END__
CD
CD
AB
CD
12
34
ab34
ab
ASSIGN ''
34
34
ASSIGN undef
Use of uninitialized value in scalar assignment at BrowserUk.substr.pl
+ line 51.
34
34
____________________________________________________
** The Third rule of perl club is a statement of fact: pod is sexy.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.