variable for field separator in perl
If you know the exact length of input, you could do this:
echo a:b:c:d | perl -F'(:)' -ane '$, = $F[1]; @F = @F[0,2,4,6]; $F[1] = 42; print @F'
If the input is of variable lengths, you'll need something more sophisticated than @f[0,2,4,6].
EDIT: -F seems to simply provide input to an automatic split() call, which takes a complete RE as an expression. You may be able to find something more suitable by reading the perldoc entries for split, perlre, and perlvar.
To sum up, what I'm looking for does not exist:
- there's no variable that holds the argument for
-F
, and more importantly - Perl's "FS" is fundamentally a different data type (regular expression) than the "OFS" (string) -- it does not make sense to join a list of strings using a regex.
Note that the same holds true in awk: FS
is a string but acts as regex:
echo a:b,c:d | awk -F'[:,]' 'BEGIN {OFS=FS} {$2=42; print}'
outputs "a[:,]42[:,]c[:,]d
"
Thanks for the insight and workarounds though.
You can use perl's -s
(similar to awk's -v
) to pass a "FS" variable, but the split
becomes manual:
echo a:b:c:d | perl -sne '
BEGIN {$, = $FS}
@F = split $FS;
$F[1] = 42;
print @F;
' -- -FS=":"