Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Unindent HERE docs

by Ovid (Cardinal)
on Feb 01, 2002 at 16:35 UTC ( #142710=snippet: print w/replies, xml ) Need Help??
Description:

This snippet was inspired by tye's post on this subject. The problem with most solutions is that they tend to be "all or nothing" unindenting. But what if you don't want unindenting (hint: use a regular HERE doc :), what if your code sometimes has tabs and sometimes has spaces for indentation? And some editors have tabs at four spaces, some at 8, etc. My solution is to provide an optional second argument to override the unindenting behavior. If you have better solutions, we could use 'em. Try the following samples with the sub:

#!/usr/bin/perl -w use strict; print unindent(<<'END'); test test2 END print unindent(<<'END', "(?: {4}|\t)"); test test2 END print unindent(<<'END', ''); I don't want this text to be unindented. END
sub unindent
{
    my ( $data, $whitespace ) = @_;
    if ( ! defined $whitespace )
    {
        ( $whitespace ) = $data =~ /^(\s+)/;
    }
    $data =~ s/^$whitespace//mg;
    $data;
}
Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: snippet [id://142710]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (5)
As of 2019-09-19 07:23 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    The room is dark, and your next move is ...












    Results (240 votes). Check out past polls.

    Notices?