| [reply] [d/l] [select] |
#!/usr/bin/perl -w
use strict;
my $var1 = 'abc~123~def';
my @fields = split(/~/,$var1);
foreach (@fields)
{
print "$_\n";
}
__END__
abc
123
def
| [reply] [d/l] |
print"$_\n"for split/~/,'abc~123~def'
| [reply] [d/l] |
perl -e'print"$_\n"for split/~/,"abc~123~def"' 41
And give you
perl -le'print for split/~/,"abc~123~def"' 37
perl -E'say for split/~/,"abc~123~def"' 34
perl -E'$_="abc~123~def";s/~/\n/g;say' 33
I guess the following is cheating
perl -E'say for abc,123,def' 23
| [reply] [d/l] [select] |
| [reply] |
$var1 = 'abc~123~def';
print join("\n",split(/\~/,$var1))."\n";
After just throwing at you, I'll try to explain it a little bit. First, I'll write it with some newlines:1 print
2 join(
3 "\n",
4 split(
5 /\~/,
6 $var1
7 )
8 ).
9 "\n";
Now let's discuss the lines. I'll take them from inside to outside because it should make the things a little bit easier to understand:
split (4) takes a string (6) and returns an array. Each element of the array is a part of the string without the given seperator (5) which must be given as a regular expression. So you could write this part as:@MyArray = split(/\~/,$var1);
The regular expression in this case has / as start and end chars and an escaped ~.
Everything is seperated now, but you also asked to print every part on a line of it's own, so we need to merge our array back to a string where every part is seperated by newlines. join (2) is perfect for this. It takes the first argument, here we have a newline (3), and puts it between every following argument returning everything as a string. Here, the following arguments are taken from the array returned by split (4). Finally, print (1) shows the result to you.
While writing this, I got a really cool idea which would fit your request but I don't think it will fit your problem. Just to be complete, here ist another solution: $var1 = 'abc~123~def';
$var1 =~ s/\~/\n/g;
print "$var1\n";
;
This one replaces every ~ with a \n using a regular expression:
=~ starts the expression
s means "replace", without it, the expression would only do a match
/ is the start char of the expression
\~ is the seperator char (escaped by \)
/ is the end char for the match part and the start char for the replacement part
\n is a newline, the thing witch should be put in place of the match part
/ is the end char
finally g means "replace all"
| [reply] [d/l] [select] |
$ perl -e '
> $var1 = q{abc~123~def};
> print join qq{\n}, split( m{~}, $var1 ), q{};'
abc
123
def
$
I hope this is of interest.
| [reply] [d/l] [select] |
thanks for the replies, very thorough. My problem was an ill placed print command.
| [reply] |