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

Unindent HERE docs

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

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;
Log In?

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

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (6)
As of 2020-09-20 18:28 GMT
Find Nodes?
    Voting Booth?
    If at first I donít succeed, I Ö

    Results (122 votes). Check out past polls.