Farewell Perl. Hello Python

This commit is contained in:
Ev Bogdanov 2017-08-17 01:04:01 +03:00
parent 9416a9e209
commit f00781edb4
2 changed files with 44 additions and 49 deletions

39
bin/s2t
View file

@ -1,19 +1,30 @@
#!/usr/bin/env perl #!/usr/bin/env python3
use strict; import sys
use warnings;
my $N_SPACES = $ARGV[0] || 4; DEFAULT_N_SPACES = 4
TAB, SPACE = ' ', ' '
while (my $line = <STDIN>) { try:
# Skip empty lines n_spaces = int(sys.argv[1])
print "\n" and next if $line !~ m/\S/; except:
n_spaces = DEFAULT_N_SPACES
$line =~ m/^(\s*)(.+)$/; if n_spaces < 1:
my $n_spaces = length($1); n_spaces = DEFAULT_N_SPACES
my $n_tabs = ($n_spaces > 0 and $n_spaces < $N_SPACES)
? 1
: int($n_spaces / $N_SPACES);
print "\t" x $n_tabs . "$2\n"; for line in sys.stdin:
} line = line.rstrip()
n_leading_spaces = 0
for ch in line:
if ch != SPACE:
break
n_leading_spaces += 1
if 0 < n_leading_spaces < n_spaces:
n_tabs = 1
else:
n_tabs = n_leading_spaces // n_spaces
print(TAB * n_tabs, line[n_leading_spaces:], sep='')

54
bin/t2s
View file

@ -1,42 +1,26 @@
#!/usr/bin/env bash #!/usr/bin/env python3
n_spaces="$1" import sys
if [ ! "$n_spaces" ]; then DEFAULT_N_SPACES = 4
n_spaces=4 TAB, SPACE = ' ', ' '
fi
if [ $n_spaces -lt 1 ]; then try:
echo 'Sorry. Number of spaces should be a positive number' n_spaces = int(sys.argv[1])
exit 1 except:
fi n_spaces = DEFAULT_N_SPACES
space='' if n_spaces < 1:
i=0 n_spaces = DEFAULT_N_SPACES
while [ true ]; do
space="$space "
i=$(( $i + 1 ))
if [ $i -eq $n_spaces ]; then
break
fi
done
while IFS='' read -r line || [[ -n "$line" ]]; do for line in sys.stdin:
if [[ ${line:0:1} != ' ' ]]; then line = line.rstrip()
echo "$line" n_tabs = 0
continue
fi
# Line length for ch in line:
line_len=${#line} if ch != TAB:
break
n_tabs += 1
# Get leading tabs and their length spaces = SPACE * n_spaces * n_tabs
tabs=$(echo "$line" | sed -n 's/^\( *\)\(.*\)$/\1/p') print(spaces, line[n_tabs:], sep='')
tabs_len=${#tabs}
line_without_tabs_len=$(( $line_len - $tabs_len ))
line_without_tabs=${line:$tabs_len:$line_without_tabs_len}
spaces=$(echo "$tabs" | sed "s/ /$space/g")
echo "$spaces$line_without_tabs"
done