PERL: sequential to CSV conversion

Tuesday, August 19, 2008

Given a file abc.txt with:

1
2
3
4
5
6
7

Here's a quick one liner to convert that to a line of CSV:

perl -e 'chomp(@data=<STDIN>);print join(",",@data),"\n";' < abc.txt

Incidentally, I tested this with a quick bash counterpart:

tr "\n" "," < abc.txt | sed 's/,$//'

After timing them both a few times, the results were pretty much the same.

BASH: Passing values from function to array

This has always been something that sort of irks me from time to time. Sure, you can pass values to an array as follows:

biteme() {
x=abc
y=123
echo $x $y
}

array=($(biteme))
echo "Element 0 is ${array[0]}, element 1 is ${array[1]}"

And you would get:

Element 0 is abc, element 1 is 123

But what if the value had a space in it? For example, change x in function biteme to abc def, and you would get:

Element 0 is abc, element 1 is def

Instead. I've always gotten around this by setting IFS to something else, say colon...then reset IFS after the function is called. For example:

biteme() {
x=abc
y=123
sp=":"
echo $x$sp$y
}

OFS=IFS;IFS=":";array=($(biteme));IFS=OFS
echo "Element 0 is ${array[0]}, element 1 is ${array[1]}"

Obviously this isn't very elegant...but it works...its either IFS or parse it through a for loop and manually assign each element in the array...if there's another way to do this I'm all ears.