Dave Tang wrote:
On Tue, 31 Mar 2009 04:49:17 +1000, John W. Krahn <jwkr...@shaw.ca> wrote:
Or instead of using arrays you could store the 1s and 0s in strings:
$ perl -le'
my $string = "10110111001";
print $-[0] while $string =~ /0/g;
'
1
4
8
9
Could you explain how the above code works please?
while $string =~ /0/g
That matches the contents of $string against the pattern /0/ globally so
each time through the while loop it will match each different '0'
character in turn.
print $-[0]
Each time through the loop print the contents of the first element of
the @- array which contains the starting position of the current match.
(The first element of the @+ array contains the ending position of the
current match.)
I looked up perl -l
in man perl and the argument is for octal. Why is that necessary?
perldoc perlrun
[ SNIP ]
-l[octnum]
enables automatic line-ending processing. It has two separate
effects. First, it automatically chomps $/ (the input record
separator) when used with -n or -p. Second, it assigns "$\"
(the output record separator) to have the value of octnum so
that any print statements will have that separator added back
on. If octnum is omitted, sets "$\" to the current value of
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
$/.
^^^
So instead of writing:
perl -e'print "something\n"'
You can write that as:
perl -le'print "something"'
And it will automatically add the newline for you.
I also looked up $-, which is the variable for the "number of lines left
on the page". Is this an array, since you use it as $-[0]?
No, the array is @-
perldoc perlvar
[ SNIP ]
@LAST_MATCH_START
@- $-[0] is the offset of the start of the last successful
match. "$-["n"]" is the offset of the start of the
substring matched by n-th subpattern, or undef if the
subpattern did not match.
By the way, you could also use index() to find the positions of the 0s
in the string:
$ perl -le'
my $string = "10110111001";
my $pos = -1;
print $pos while ( $pos = index $string, "0", ++$pos ) >= 0;
'
1
4
8
9
John
--
Those people who think they know everything are a great
annoyance to those of us who do. -- Isaac Asimov
--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/