in reply to split and print

$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"
  • Replies are listed 'Best First'.
    Re^2: split and print
    by johngg (Canon) on Sep 04, 2009 at 21:25 UTC
      print join("\n",split(/\~/,$var1))."\n";

      Rather than concatenating a newline why not place an empty string at the end of the things to be joined.

      $ perl -e ' > $var1 = q{abc~123~def}; > print join qq{\n}, split( m{~}, $var1 ), q{};' abc 123 def $

      I hope this is of interest.

      Cheers,

      JohnGG

    Re^2: split and print
    by sans-clue (Beadle) on Sep 04, 2009 at 20:58 UTC
      thanks for the replies, very thorough. My problem was an ill placed print command.