Choosing The Right Server-Side Scripting Language
By Craig McElwee
2004-01-06
Reader Rating:

Task 6: Split Comma-Delimited Line Into Variables
Your script reads a line from a CSV file. How easily does it separate each field into individual variables, in this case, a, b, c, and d? Perl, PHP, and Python all have a handy 'split' function, taking the string to be split and the delimiter used for splitting as arguments. Java servlets and Tcl require you to set each field individually. While fine for this example, this latter approach would be prohibitive if each line had a large number of fields.
Perl:
($a,$b,$c,$d) = split /,/, $lines[@lines-1];
|
PHP:
list( $a,$b,$c,$d ) = split( ",", $last, 4 );
|
Python:
a,b,c,d = splitfields(lines[-1], ',')
|
Java:
String a, b, c, d;
StringTokenizer st = new StringTokenizer(last, ",");
a = st.nextToken();
b = st.nextToken();
c = st.nextToken();
d = st.nextToken();
|
Tcl:
set fieldlist [split $last ,]
set a [lindex $fieldlist 0]
set b [lindex $fieldlist 1]
set c [lindex $fieldlist 2]
set d [lindex $fieldlist 3]
|
First published by IBM developerWorks
If you found this article interesting, you may want to read these as well:
» Protecting your PHP and HTML Source Code
» Publishing Newsletters Using PHP & MySQL - 4
» Publishing Newsletters Using PHP & MySQL - 3
» Publishing Newsletter Using PHP & MySQL - 2
» Publishing Newsletters Using PHP & MySQL
» Unix Webserver Crontab Basics
|