ЭЛЕКТРОННАЯ БИБЛИОТЕКА КОАПП |
Сборники Художественной, Технической, Справочной, Английской, Нормативной, Исторической, и др. литературы. |
1.7. Expanding and Compressing TabsProblemYou want to convert tabs in a string to the appropriate number of spaces, or vice versa. Converting spaces into tabs can be used to reduce file size when the file has many consecutive spaces. Converting tabs into spaces may be required when producing output for devices that don't understand tabs or think they're at different positions than you do. SolutionEither use a rather funny looking substitution: while ($string =~ s/\t+/' ' x (length($&) * 8 - length($`) % 8)/e) { # spin in empty loop until substitution finally fails } Or the standard Text::Tabs module: use Text::Tabs; @expanded_lines = expand(@lines_with_tabs); @tabulated_lines = unexpand(@lines_without_tabs); DiscussionAssuming that tab stops are set every N positions (where N is customarily eight), it's easy to convert them into spaces. The standard, textbook method does not use the Text::Tabs module but suffers from being difficult to understand. Also, it uses the while (<>) { 1 while s/\t+/' ' x (length($&) * 8 - length($`) % 8)/e; print; } If you're looking at the second The obscure convention The standard Text::Tabs module provides conversion functions to convert both directions, exports a use Text::Tabs; $tabstop = 4; while (<>) { print expand($_) } We can also use Text::Tabs to "unexpand" the tabs. This example uses the default use Text::Tabs; while (<>) { print unexpand($_) } See AlsoThe manpage for the Text::Tabs module (also in Chapter 7 of Programming Perl); the |