Perl Programming Page 2 - Perl Lists: The Split() Function |
In our previous examples, we used a single character as our delimiter. But we aren't limited (pun intended) to that single character. Below are some examples using strings as a delimiter: #!/usr/bin/perl $Message = "Hidden Message: ----K----i----ll----yo----urse----lf\n\n"; @DoIt = split(/----/,$Message); print @DoIt[0]; print @DoIt[1]; print @DoIt[2]; print @DoIt[3]. " "; print @DoIt[4]; print @DoIt[5]; print @DoIt[6]; Here our delimiter is “----”. The output of this nefarious code is: Hidden Message: Kill yourself You can also use a variable as your delimiter, like so: #!/usr/bin/perl $Message = "Hidden Message: ----K----i----ll----yo----urse----lf\n\n"; $Del = "----"; @DoIt = split(/$Del/,$Message); print @DoIt[0]; print @DoIt[1]; print @DoIt[2]; print @DoIt[3]. " "; print @DoIt[4]; print @DoIt[5]; print @DoIt[6]; This gives us the same result as before. If you want to get creative, you could also use a list. In this next example, we will create a string with several possible delimiters, and then use a list to switch back and forth between them: #!/usr/bin/perl $Data = "Here is some data: Apple,9~Beer,9~Cider\n\n"; @Del = (',','9','~',); @Comma = split(/@Del[0]/,$Data); @Nine = split(/@Del[1]/,$Data); @Weird = split(/@Del[2]/,$Data); print @Comma[0]; print @Comma[1]; print @Comma[2]; print @Comma[3]; print @Nine[0]; print @Nine[1]; print @Nine[2]; print @Nine[3]; print @Weird[0]; print @Weird[1]; print @Weird[2]; print @Weird[3]; This results in the following: Here is some data: Apple9~Beer9~Cider Here is some data: Apple,~Beer,~Cider Here is some data: Apple,9Beer,9Cider
blog comments powered by Disqus |
|
|
|
|
|
|
|