Assigning a string to Perl substr?

I am looking at Perl script written by someone else, and I found this:

$num2 = '000000';
substr($num2, length($num2)-length($num), length($num)) = $num;
my $id_string = $text."_".$num2

Forgive me ignorance, but for an untrained Perl programmer the second line looks as if the author is assigning the string $num to the result of the function substr. What does this line exactly do?


In Perl, (unlike say, Python, where strings, tuples are not modifiable in-place), strings can be modified in situ. That is what substr is doing here, it is modifying only a part of the string. Instead of this syntax, you can use the more cryptic syntax:

substr($num2, length($num2)-length($num), length($num),$num);

which accomplishes the same thing. You can further stretch it. Imagine you want to replace all instances of foo by bar in a string, but only within the first 50 characters. Perl will let you do it in a one-liner:

substr($target,0,50) =~ s/foo/bar/g;

Great, isn't it?

Exactly what you think it would do:

$ perldoc -f substr

You can use the substr() function as an lvalue, in which case EXPR must itself be an lvalue. If you assign something shorter than LENGTH, the string will shrink, and if you assign something longer than LENGTH, the string will grow to accommodate it. To keep the string the same length, you may need to pad or chop your value using "sprintf".

Need Your Help

Global “using” directives in VS2010/C#?

c# visual-studio-2010 using-statement using-directives .net-4.0

I'm pretty sure I know the answer but I'm wondering if there's a way to define a global "using" directive in my C# projects so that I don't have to repeat the directive on top of every code file.

How to overwrite a file in java

java io java-io

in my program, I am trying to read the file and then trying to overwrite the file using txtFile method. f is the file which i am reading and doing operations on its contents and now want to replace...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.