출처 : http://www.perlmeme.org/howtos/perlfunc/
Using the Perl chomp() function
Introduction
The chomp()
function will remove (usually) any newline character from the end of a string. The reason we say usually is that it actually removes any character that matches the current value of $/ (the input record separator), and $/ defaults to a newline.
For more information on the $/ variable, try perldoc perlvar
and see the entry for $/.
Example 1. Chomping a string
Most often you will use chomp()
when reading data from a file or from a user. When reading user input from the standard input stream (STDIN) for instance, you get a newline character with each line of data. chomp()
is really useful in this case because you do not need to write a regular expression and you do not need to worry about it removing needed characters.
When running the example below, using the enter key on a line by itself will exit the program.
#!/usr/bin/perl use strict; use warnings; while (my $text = <STDIN>) { chomp($text); print "You entered '$text'\n"; last if ($text eq ''); }
Example usage and output of this program is:
a word You entered 'a word' some text You entered 'some text' You entered ''
Example 2. Chomping an array
If you chomp an array, it will remove a newline from the end of every element in the array:
#!/usr/bin/perl use strict; use warnings; my @array = ("bob\n", "jill", "fred\n"); print "Before chomp:\n"; print "@array\n"; chomp(@array); print "After chomp:\n"; print "@array\n";
This program produces the following output:
Before chomp: bob jill fred After chomp: bob jill fred
As you can see, the newlines have been removed from "bob" and "fred", but no characters have been removed from "jill".
Example 3. Chomping a hash
If you pass a hash into chomp()
, it will remove newlines from every value (not key) of the hash:
#!/usr/bin/perl use strict; use warnings; my %hash = ( 'first' => "one\n", 'second' => "two\n", 'third' => "three\n", ); chomp(%hash); foreach my $k (keys %hash) { print "$k: $hash{$k} "; } print "\n"; exit 0;
This program outputs:
first: one second: two third: three
See also
Using the Perl chop() function
Introduction
Sometimes you will find you want to unconditionally remove the last character from a string. While you can easily do this with regular expressions, chop
is more efficient.
The chop()
function will remove the last character of a string (or group of strings) regardless of what that character is. Note, if you want to easily remove newlines or line separators see the chomp() howto.
Example 1. Chopping a string
The chop()
function removes and returns the last character from the given string:
#!/usr/bin/perl use strict; use warnings; my $string = 'frog'; my $chr = chop($string); print "String: $string\n"; print "Char: $chr\n";
This program gives you:
String: fro Char: g
If the string is empty, chop()
will return an empty string. If the string is undefined, chop()
will return undefined.
Example 2. Chopping strings in an array
If you pass the chop()
function an array, it will remove the last character from every element in the array.
Note that this will only work for a one-dimensional array. In other words, it is not valid to pass in an array reference, or an array that contains an array (or hash).
#!/usr/bin/perl use strict; use warnings; my @array = ('fred', 'bob', 'jill', 'joan'); my $chr = chop(@array); foreach my $str (@array) { print "$str\n"; } print "Char: $chr\n";
This produces the output:
fre bo jil joa Char: n
Example 3. Chopping strings in a hash
If you pass a hash into chop()
, it will remove the last character from the values (not the keys) in the hash. For example:
#!/usr/bin/perl use strict; use warnings; my %hash = ( first => 'one', second => 'two', third => 'three', ); my $chr = chop(%hash); foreach my $k (keys %hash) { print "$k: $hash{$k}\n"; } print "Char: $chr\n";
This program outputs:
first: on second: tw third: thre Char: e
Note that as with arrays, chop is not designed to process hash reference or hashes containing other hashes (or arrays).
Introduction
The index()
function is used to determine the position of a letter or a substring in a string. For example, in the word "frog" the letter "f" is in position 0, the "r" in position 1, the "o" in 2 and the "g" in 3. The substring "ro" is in position 1. Depending on what you are trying to achieve, the index()
function may be faster or more easy to understand than using a regular expression or the split()
function.
Example 1a. Where in a string is a certain letter?
Let's say you are trying to determine if a word has a particular letter in it. Let's look for the letter "l" in the string "perlmeme.org".
#!/usr/bin/perl use strict; use warnings; my $string = 'perlmeme.org'; my $char = 'l'; my $result = index($string, $char); print "Result: $result\n";
This program gives you:
Result: 3
Example 1b. The string doesn't contain the letter?
If the string doesn't contain the letter, index()
will return a -1. For example, we can look for the letter "L" in the string "perlmeme.org":
#!/usr/bin/perl use strict; use warnings; my $string = 'perlmeme.org'; my $char = 'L'; my $result = index($string, $char); print "Result: $result\n";
The program outputs:
Result: -1
Example 1c. The string contains more than one of the letter?
If the letter we're searching for appears more than once in the string, index()
return the index of the first occurrence of the letter.
#!/usr/bin/perl use strict; use warnings; my $string = 'perlmeme.org'; my $char = 'e'; my $result = index($string, $char); print "Result: $result\n";
This program gives you:
Result: 1
Example 2. Looking for a substring
Looking for a substring (rather than a single character) works in exactly the same way as looking for a single character:
#!/usr/bin/perl use strict; use warnings; my $string = 'perlmeme.org'; my $substr = 'me'; my $result = index($string, $substr); print "Result: $result\n";
This program gives you:
Result: 4
Example 3a. What if I don't want the first occurrence?
The index()
function let's you specify an offset. This tells index()
where to start looking in the string. In our example, we found the first occurrence of the letter 'e' at position 1. Let's try to find the second:
#!/usr/bin/perl use strict; use warnings; my $string = 'perlmeme.org'; my $char = 'e'; # The first 'e' was at position 1, so let's start # looking again at position 2 my $offset = 2; my $result = index($string, $char, $offset); print "Result: $result\n";
The program outputs:
Result: 5
Example 3b. How to find every occurrence
To find (and do something with) every occurrence of a character in a string, you could use index()
in a loop, incrementing the offset each time:
#!/usr/bin/perl use strict; use warnings; my $string = 'perlmeme.org'; my $char = 'e'; my $offset = 0; my $result = index($string, $char, $offset); while ($result != -1) { print "Found $char at $result\n"; $offset = $result + 1; $result = index($string, $char, $offset); }
When we run this program, we get the following output:
Found e at 1 Found e at 5 Found e at 7
Example 4. How to find the last occurrence
Instead of looping through every occurrence of a letter in a string to find the last one, you can use the rindex()
function. This works exactly the same as index()
but it starts at the end of the string. The index value returned is string from the start of the string though.
#!/usr/bin/perl use strict; use warnings; my $string = 'perlmeme.org'; my $char = 'e'; my $result = rindex($string, $char); print "Result: $result\n";
This would produce:
Result: 7
For more information on rindex()
see our rindex() howto.
Using the Perl push() function
Introduction
You can use the push
function to add new elements to the end of an array.
Example 1. Adding an item onto an array
You can use push
to push an element onto the end of an array:
#!/usr/bin/perl use strict; use warnings; my @planets = qw(mercury venus earth mars); print "@planets\n"; push (@planets, 'jupiter'); print "@planets\n"; exit 0;
This program produces the following output:
mercury venus earth mars mercury venus earth mars jupiter
You can see that 'jupiter' is now on the end of our @planets
array.
The push
function returns the number of elements in the array after the new value(s) have been appended. If we wanted to see how many planets were in the modified @planets
array, we could change our code as follows:
#!/usr/bin/perl use strict; use warnings; my @planets = qw(mercury venus earth mars); print "@planets\n"; my $number_of_planets = push (@planets, 'jupiter'); print "@planets\n"; print "The number of planets is: $number_of_planets\n"; exit 0;
The output is now:
mercury venus earth mars mercury venus earth mars jupiter The number of planets is: 5
Example 2. Joining two arrays together
You can also use push
to append an array onto the end of another array:
#!/usr/bin/perl use strict; use warnings; my @planets = qw(mercury venus earth mars); my @outer_planets = qw(jupiter saturn uranus neptune pluto); print "@planets\n"; push (@planets, @outer_planets); print "@planets\n"; exit 0;
As the following output demonstrates, the @outer_planets
array has been added to the end of the @planets
array:
mercury venus earth mars mercury venus earth mars jupiter saturn uranus neptune pluto
Example 3. Adding to an array reference
You can use push
to append elements onto the end of a reference to an array, but you must dereference it first:
#!/usr/bin/perl use strict; use warnings; my @planets = qw(mercury venus earth mars); my $planets_ref = \@planets; push ( @{ $planets_ref }, qw(jupiter saturn uranus neptune pluto)); # Could also be written as: # push ( @$planets_ref, qw(jupiter saturn uranus neptune pluto)); print "@{ $planets_ref }\n"; # Could also be written as: # print "@$planets_ref\n"; exit 0;
This produces the following output:
mercury venus earth mars jupiter saturn uranus neptune pluto
Using the Perl qw() function
Introduction
The 'quote word' function
qw()
is used to generate a list of words. If takes a string such as:tempfile tempdirand returns a quoted list:
'tempfile', 'tempdir'saving you from the tedium of having to quote and comma-separate each element of the list by hand. Here's a full example:
#!/usr/bin/perl use strict; use warnings; use File::Temp qw(tempfile tempdir);This code fragment has the effect of importing the
tempfile
andtempdir
functions from theFile::Temp
module. It does this by providing the list'tempfile', 'tempdir'
to theuse
function.How it works
qw()
extracts words out of your string using embedded whitsepace as the delimiter and returns the words as a list. Note that this happens at compile time, which means that the call toqw()
is replaced with the list before your code starts executing.Convenience
The
qw()
function is one of the many ways in which Perl helps to make it easier to write code. Wherever you need to construct a list like this:my @names = ('Kernighan', 'Ritchie', 'Pike');you can use
qw
to do the same thing more simply:my @names = qw(Kernighan Ritchie Pike);Delimeters
You can use any non-alphanumeric, non-whitespace delimeter to surround the
qw()
string argument. You'll often seeqw//
, for example.If you use any of the bracketing characters
(
,<
,[
or{
as your delimeter, you'll have to close with a matching bracket.So the following are equivalent:
@names = qw(Kernighan Ritchie Pike); @names = qw/Kernighan Ritchie Pike/; @names = qw'Kernighan Ritchie Pike'; @names = qw{Kernighan Ritchie Pike};Additionlly, no interpolation is possible in the string you pass to
qw()
.This code fragment:
#!/usr/bin/perl use strict; use warnings; my $developer = 'Thompson'; my @names = qw(Kernighan Ritchie Pike $developer); foreach my $name (@names) { print "name: $name\n"; }Will output:
name: Kernighan name: Ritchie name: Pike name: $developerQuotes as operators
In Perl, quotes are considered operators. We have dealt with
qw()
here as if it was a function, (and indeed it is listed as such in the standard perlfunc documentation), but this is not the whole story. In order to get a better picture of the subtlety of Perl's quoting, see the following section in the perlop documentation:Quote and Quote-like Operators Regexp Quote-Like OperatorsUsing the Perl rand() function
Introduction
The
rand()
function is used to generate random numbers. By default it generates a number between 0 and 1, however you can pass it a maximum and it will generate numbers between 0 and that number.Example 1. Between 0 and 1
To generate a random decimal number between 0 and 1, use
rand()
without any parameters.#!/usr/bin/perl use strict; use warnings; my $random_number = rand(); print $random_number . "\n";This will give you a random number, like:
0.521563085335405Example 2. A bigger range of numbers
Quite often you don't want a number between 0 and 1, but you want a bigger range of numbers. If you pass
rand()
a maximum, it will return a decimal number between 0 and that number. Our example below generates a random number between 0 and 100.#!/usr/bin/perl use strict; use warnings; my $range = 100; my $random_number = rand($range); print $random_number . "\n";The program will produce something like:
34.0500569277541Example 3. A random integer
To generate a random integer, convert the output from rand to an integer, as follows:
#!/usr/bin/perl use strict; use warnings; my $range = 100; my $random_number = int(rand($range)); print $random_number . "\n";This program gives you an integer from 0 to 99 inclusive:
68Example 4. With an offset
To generate a random number between, for example, 100 and 150, simply work out the range and add the minimum value to your random number.
#!/usr/bin/perl use strict; use warnings; my $range = 50; my $minimum = 100; my $random_number = int(rand($range)) + $minimum; print $random_number . "\n";This program gives you:
129Using the Perl rindex() function
Introduction
The
rindex()
function is used to determine the position of a character in a string starting at the end of the string. We recommend that you first read our index() howto.
rindex()
works exactly the same asindex()
except that it returns the index of the last occurrence of a letter or substring in the string.Example 1a. Finding the last occurrence of a letter in a string.
We want to find the last occurrence of the letter "m" in the string "perlmeme.org".
#!/usr/bin/perl use strict; use warnings; my $string = 'perlmeme.org'; my $char = 'm'; my $result = rindex($string, $char); print "Result: $result\n";This program gives you:
Result: 6Example 1b. The string doesn't contain the letter?
Just like for
index()
if the string doesn't contain the letter,rindex()
will return a -1. For example, we can look for the letter "L" in the string "perlmeme.org":#!/usr/bin/perl use strict; use warnings; my $string = 'perlmeme.org'; my $char = 'L'; my $result = rindex($string, $char); print "Result: $result\n";The program outputs:
Result: -1Example 2a. The string contains more than one of the letter?
If the letter we're searching for appears more than once in the string,
rindex()
return the index of the first occurrence of the letter.#!/usr/bin/perl use strict; use warnings; my $string = 'perlmeme.org'; my $char = 'e'; my $result = rindex($string, $char); print "Result: $result\n";This program gives you:
Result: 7Example 2b. What if I want the second last occurrence?
The offset parameter for
rindex()
works slightly differently to the offset parameter forindex()
.In
index()
the character of substring will be searched for starting at the offset position. For example, the first occurrence of the letter 'e' in the string "perlmeme.org" is at position 1. If we want to find the second occurrence, we set the offset to 2.With
rindex()
we start at the offset position and look backwards. The last occurrence of the letter 'e' is at position 7. So to find the second last occurrence we set the offset to 6.#!/usr/bin/perl use strict; use warnings; my $string = 'perlmeme.org'; my $char = 'e'; # The first 'e' was at position 1, so let's start # looking again at position 2 my $offset = 6; my $result = rindex($string, $char, $offset); print "Result: $result\n";The program outputs:
Result: 5Example 2c. How to find every occurrence
To find (and do something with) every occurrence of a character in a string using
rindex()
, you could useindex()
in a loop, decrementing the offset each time. Note that when using an offset, we need to tellrindex()
to start at the back of the string (otherwise it starts at 0 which returns no results).#!/usr/bin/perl use strict; use warnings; my $string = 'perlmeme.org'; my $char = 'e'; # Start at the end of the string my $offset = length($string); my $result = rindex($string, $char, $offset); while ($result != -1) { print "Found $char at $result\n"; $offset = $result - 1; $result = rindex($string, $char, $offset); }When we run this program, we get the following output:
Found e at 7 Found e at 5 Found e at 1Sorting
The sort function sorts a list (an array). The default is to sort alphabetically. However, you can define your own sorts to get around numbers and complex data structures.
Sort an array of strings
#!/usr/bin/perl use strict; use warnings; my @strings = ("Becky", "Simon", "Bianca", "Steven", "Greg", "Andrew"); my @sorted_strings = sort @strings; print "@sorted_strings\n";This gives you the following output:
Andrew Becky Bianca Greg Simon StevenSort an array of numbers
The Perl sort function sorts by strings instead of by numbers. If you were to use:
#!/usr/bin/perl use strict; use warnings; my @numbers = (23, 1, 22, 7, 109, 9, 65, 3); my @sorted_numbers = sort @numbers; print "@sorted_numbers\n";The output you would see would be:
1 109 22 23 3 65 7 9To sort numerically, declare your own sort block and use the flying saucer operator <=>:
#!/usr/bin/perl use strict; use warnings; my @numbers = (23, 1, 22, 7, 109, 9, 65, 3); my @sorted_numbers = sort {$a <=> $b} @numbers; print "@sorted_numbers\n";The output would now be:
1 3 7 9 22 23 65 109Note that $a and $b do not need to be declared, even with use strict on, because they are special sorting variables.
To find out more, see the tutorial Sorting in perl, or run the command:
perldoc -f sortUsing the Perl split() function
Introduction
The
split()
function is used to split a string into smaller sections. You can split a string on a single character, a group of characers or a regular expression (a pattern).You can also specify how many pieces to split the string into. This is better explained in the examples below.
Example 1. Splitting on a character
A common use of
split()
is when parsing data from a file or from another program. In this example, we will split the string on the comma ','. Note that you typically should not usesplit()
to parse CSV (comma separated value) files in case there are commas in your data: use Text::CSV instead.#!/usr/bin/perl use strict; use warnings; my $data = 'Becky Alcorn,25,female,Melbourne'; my @values = split(',', $data); foreach my $val (@values) { print "$val\n"; } exit 0;This program produces the following output:
Becky Alcorn 25 female MelbourneExample 2. Splitting on a string
In the same way you use a character to split, you can use a string. In this example, the data is separated by three tildas '~~~'.
#!/usr/bin/perl use strict; use warnings; my $data = 'Bob the Builder~~~10:30am~~~1,6~~~ABC'; my @values = split('~~~', $data); foreach my $val (@values) { print "$val\n"; } exit 0;This outputs:
Bob the Builder 10:30am 1,6 ABCExample 3. Splitting on a pattern
In some cases, you may want to split the string on a pattern (regular expression) or a type of character. We'll assume here that you know a little about regular expressions. In this example we will split on any integer:
#!/usr/bin/perl use strict; use warnings; my $data = 'Home1Work2Cafe3Work4Home'; # \d+ matches one or more integer numbers my @values = split(/\d+/, $data); foreach my $val (@values) { print "$val\n"; } exit 0;The output of this program is:
Home Work Cafe Work HomeExample 4. Splitting on an undefined value
If you split on an undefined value, the string will be split on every character:
#!/usr/bin/perl use strict; use warnings; my $data = 'Becky Alcorn'; my @values = split(undef,$data); foreach my $val (@values) { print "$val\n"; } exit 0;The results of this program are:
B e c k y A l c o r nExample 5. Splitting on a space
If you use a space ' ' to split on, it will actually split on any kind of space including newlines and tabs (regular expression /\s+/) rather than just a space. In this example we print 'aa' either side of the values so we can see where the split took place:
#!/usr/bin/perl use strict; use warnings; my $data = "Becky\n\nAlcorn"; my @values = split(' ',$data); # Print 'aa' either side of the value, so we can see where it split foreach my $val (@values) { print "aa${val}aa\n"; } exit 0;This produces:
aaBeckyaa aaAlcornaaAs you can see, it has split on the newlines that were in our data. If you really want to split on a space, use regular expressions:
my @values = split(/ /,$data);Example 6. Delimiter at the start of the string
If the delimiter is at the start of the string then the first element in the array of results will be empty. We'll print fixed text with each line so that you can see the blank one:
#!/usr/bin/perl use strict; use warnings; my $data = ',test,data'; my @values = split(',',$data); # We print "Val: " with each line so that you can see the blank one foreach my $val (@values) { print "Val: $val\n"; } exit 0;The output of this program is:
Val: Val: test Val: dataExample 7. Split and context
If you do not pass in a string to split, then
split()
will use $_. If you do not pass an expression or string to split on, thensplit()
will use ' ':#!/usr/bin/perl use strict; use warnings; foreach ('Bob the Builder', 'Thomas the TankEngine', 'B1 and B2') { my @values = split; print "Split $_:\n"; foreach my $val (@values) { print " $val\n"; } } exit 0;This produces:
Split Bob the Builder: Bob the Builder Split Thomas the TankEngine: Thomas the TankEngine Split B1 and B2: B1 and B2Example 8. Limiting the split
You can limit the number of sections the string will be split into. You can do this by passing in a positive integer as the third argument. In this example, we're splitting our data into 3 fields - even though there are 4 occurrances of the delimiter:
#!/usr/bin/perl use strict; use warnings; my $data = 'Becky Alcorn,25,female,Melbourne'; my @values = split(',', $data, 3); foreach my $val (@values) { print "$val\n"; } exit 0;This program produces:
Becky Alcorn 25 female,MelbourneExample 9. Keeping the delimiter
Sometimes, when splitting on a pattern, you want the delimiter in the result of the split. You can do this by capturing the characters you want to keep inside parenthesis. Let's do our regular expression example again, but this time we'll keep the numbers in the result:
#!/usr/bin/perl use strict; use warnings; my $data = 'Home1Work2Cafe3Work4Home'; # \d+ matches one or more integer numbers # The parenthesis () mean we keep the digits we match my @values = split(/(\d+)/, $data); foreach my $val (@values) { print "$val\n"; } exit 0;The output is:
Home 1 Work 2 Cafe 3 Work 4 HomeExample 10. Splitting into a hash
If you know a bit about your data, you could split it directly into a hash instead of an array:
#!/usr/bin/perl use strict; use warnings; my $data = 'FIRSTFIELD=1;SECONDFIELD=2;THIRDFIELD=3'; my %values = split(/[=;]/, $data); foreach my $k (keys %values) { print "$k: $values{$k}\n"; } exit 0;The output of this program is:
FIRSTFIELD: 1 THIRDFIELD: 3 SECONDFIELD: 2The problem is that if the data does not contain exactly what you think, for example
FIRSTFIELD=1;SECONDFIELD=2;THIRDFIELD=
then you will get an 'Odd number of elements in hash assignment' warning. Here is the output of the same program but with this new data:
Using the Perl substr() function
Introduction
The
substr()
function is used to return a substring from the expression supplied as it's first argument. The function is a good illustration of some of the ways in which Perl is different from other languages you may have used.substr()
has a variable number of arguments, it can be told to start at an offset from either end of the expression, you can supply a replacement string so that it replaces part of the expression as well as returning it, and it can be assigned to!Example 1a. Supply an expression and a positive offset value.
In our first example, we'll use
$string
as the first argument, or expression, and supply the offset argument to indicate how far from the left side of the expression our substring should start. Sincesubstr()
returns the substring that it matches, we assign this value to$fragment
#!/usr/bin/perl use strict; use warnings; my $string = 'Now is the time for all good people to come to the aid of their party'; my $fragment = substr $string, 4; print " string: <$string>\n"; print "fragment: <$fragment>\n";This script produces the following output:
string: <Now is the time for all good people to come to the aid of their party> fragment: <is the time for all good people to come to the aid of their party>In
$string
, the 'i' in the word 'is' is at offset four, because the function starts counting at zero. Therefore the letter 'N' is at offset 0, 'o' is at offset 1, 'w' is at offset 2, and so on.Example 1b. Supply an expression and a positive offset value.
If we increase the offset to 7, the substring return by
substr()
starts at the word 'the'.#!/usr/bin/perl use strict; use warnings; my $string = 'Now is the time for all good people to come to the aid of their party'; my $fragment = substr $string, 7; print " string: <$string>\n"; print "fragment: <$fragment>\n";string: <Now is the time for all good people to come to the aid of their party> fragment: <the time for all good people to come to the aid of their party>Example 1c. Supply an expression and a positive offset value.
In this example, instead of an explicit offset argument, we'll use the
index()
function to determine the position of the word 'people'.#!/usr/bin/perl use strict; use warnings; # Find the location of the substring 'people' my $string = 'Now is the time for all good people to come to the aid of their party'; my $fragment = substr $string, index($string, 'people'); print " string: <$string>\n"; print "fragment: <$fragment>\n";string: <Now is the time for all good people to come to the aid of their party> fragment: <people to come to the aid of their party>Example 2a. Supply an expression, a positive offset value and a length
We can supply a third argument to
substr()
, to limit the size of the substring that is returned. This is the length argument.#!/usr/bin/perl use strict; use warnings; my $string = 'Now is the time for all good people to come to the aid of their party'; my $length = 8; my $fragment = substr $string, 7, $length; print " string: <$string>\n"; print "fragment: <$fragment>\n";Now we're starting at offset 7 and only returning
$length
bytes.string: <Now is the time for all good people to come to the aid of their party> fragment: <the time>Example 2b. Supply an expression, a negative offset value and a length
If we supply a negative offset value, then
substr()
starts that many characters from the end of the string. Here our offset is -16. which means that our substring will start at the word 'aid', and since our length argument is 10, the function returns the string 'd of their'.#!/usr/bin/perl use strict; use warnings; my $string = 'Now is the time for all good people to come to the aid of their party'; my $length = 10; my $fragment = substr $string, -16, $length; print " string: <$string>\n"; print "fragment: <$fragment>\n";string: <Now is the time for all good people to come to the aid of their party> fragment: <d of their>Example 2c. Supply an expression, a positive offset value and a negative length
If we supply a negative length argument, then that many characters are truncated off the end of the string.
#!/usr/bin/perl use strict; use warnings; my $string = 'Now is the time for all good people to come to the aid of their party'; my $length = -20; my $fragment = substr $string, 7, $length; print " string: <$string>\n"; print "fragment: <$fragment>\n";string: <Now is the time for all good people to come to the aid of their party> fragment: <the time for all good people to come to th>Supplying negative arguments might seem weird, but that's OK, because Perl is weird. These negative arguments save you the bother of having to work out where the end of the string is. (And that can be very useful).
Example 3. An expression, an offset value, a length and a replacement value
It's time to confess something. The string we've been using in our examples is an old typing exercise. The original typist's example assumed that only good men could come to the aid of their party! So let's supply the word 'men' as the fourth argument, and see that
substr()
then modifies$string
, returning it to it's old-fashioned form.#!/usr/bin/perl use strict; use warnings; my $string = 'Now is the time for all good people to come to the aid of their party'; my $fragment = substr $string, index($string, 'people'), 6, 'men'; print " string: <$string>\n"; print "fragment: <$fragment>\n";string: <Now is the time for all good men to come to the aid of their party> fragment: <people>As you can see, our call to
substr()
has replaced the word 'people' with the word 'men'. By supplying a fourth argument, we have modified the expression$string
. At the same time,substr()
still returns the substring 'people'.Example 4. Assigning to substr()
It is perhaps more common to see the modification demonstrated in the previous example achieved by direct assignment. In technical terms, this means that the
substr()
function can be used as an lvalue, something that can be assigned a value.#!/usr/bin/perl use strict; use warnings; my $string = 'Now is the time for all good people to come to the aid of their party'; substr($string, index($string, 'people'), 6) = 'women'; print " string: <$string>\n";string: <Now is the time for all good women to come to the aid of their party>
'perl' 카테고리의 다른 글
Array 다루기 #1 (0) | 2008.06.05 |
---|---|
Passing Parameters to Functions (0) | 2008.06.05 |
bash는 float 변수 연산이 안된다. (0) | 2007.10.21 |
펄 해쉬 이야기 #2 (0) | 2007.10.19 |
펄 Hash 관련 정보 #1 (0) | 2007.10.19 |