Perl code to convert from CSH to BASH??
am 27.01.2008 09:56:13 von ahmad
Hi,
I was trying to write a Perl code to be used to convert CSH scripts to
BASH. I target to translate .cshrc file to .bashrc one.
My question is: In converting "path" setting statement i was trying
to use "join" and "split" functions.
For example:
set path = (/bin /usr/bin /sbin $HOME/bin ) ===> export PATH=$PATH:/
bin:/usr/bin:/sbin:$HOME/bin
I wrote the part of Perl code like that ($a is holding the line to be
converted):
$a=~s/[()]//g ; # To remove parentheses
$a=~s/set\s+path\s+=(.+)/export PATH=\$PATH:/g;
$b=join(':',split(/\s+/,$1);
$a.=$b;
print FID $a;
And it worked fine, but as you see, the code is very long to convert a
very small part.. Is it possible to include and evaluate function
within the RE replacement side?
Something like that: $a=s/....../....FUNCTION TO BE EVALUATED (e.g.
join.....)..../eg;
How can i do it?
Thanks a lot in advance,
Regards,
Ahmad
P.S. If anyone knows an easiest way to convert from csh to bash, or
had already written a script that does that, please tell me about it..
Thanks a lot.
Re: Perl code to convert from CSH to BASH??
am 27.01.2008 17:07:00 von Henry Law
Ahmad wrote:
> For example:
>
> set path = (/bin /usr/bin /sbin $HOME/bin ) ===> export PATH=$PATH:/
> bin:/usr/bin:/sbin:$HOME/bin
>
> I wrote the part of Perl code like that ($a is holding the line to be
> converted):
Don't do that. (1) Better to use variables that mean something; (2) $a
and $b are used in the "sort" statement and are, by convention, reserved
for that use.
> How can i do it?
Having not a lot better to do this afternoon I had a look at this.
Remember that converting the "set path" statement isn't the only thing
you need to. I don't know csh but I know at least that you'll need to
convert the shebang, and probably a whole lot of other lines as well.
So you're really writing a loop that reads in the csh line by line and
converts each one as appropriate. Here's a starter; it does the "export
path" statement as you requested, and also the shebang. You can add
more "elsif" sections for the other things you need to convert.
#! /usr/bin/perl
use strict;
use warnings;
while ( my $line = ) {
if ( $line =~ /^set\s+path\s?=\s?\((.*)\)/ ) {
# Process lines containing set path = ( /some/stuff )
# (You could refine the pattern inside the capturing brackets;
# something like [\w\s/\$] comes to mind)
my @path_elements = split /\s+/,$1;
print "export PATH=\$PATH:", join( ':', @path_elements ), "\n";
} elsif ( $line =~ m|^\#!/usr/bin/csh| ) {
# Process the shebang line
print "\#!/usr/bin/bash\n";
} else {
print $line;
}
}
__DATA__
#!/usr/bin/csh
#
set path = (/bin /usr/bin /sbin $HOME/bin )
--
Henry Law Manchester, England