Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

splicepath

by casiano (Pilgrim)
on Oct 13, 2008 at 22:00 UTC ( [id://716869]=sourcecode: print w/replies, xml ) Need Help??
Category: Utility Scripts
Author/Contact Info Casiano
Description: Like Perl splice operator but works on PATH-like environment variables, i.e. lists whose elements are separated by colons
#!/usr/bin/perl -w
use strict;
use Getopt::Long;

my $VAR        = 'PATH';
my $OFFSET     = 0;
my $LENGTH     = 0;
my $EXECUTABLE = '';
my $EVAL       = 1;

my @LIST;

GetOptions(
    '-variable=s'   => \$VAR,
    '-offset=i'     => \$OFFSET,
    '-length=i'     => \$LENGTH,
    '-executable=s' => \$EXECUTABLE,
    '-bashsource!'  => \$EVAL,
);

exit(1) unless $ENV{$VAR};

my @P = split ':', $ENV{$VAR};
local $" = ':';
if ($EXECUTABLE) {
    @LIST = `$EXECUTABLE`;
    chomp @LIST;
}
else {
    @LIST = @ARGV;
}
splice @P, $OFFSET, $LENGTH, @LIST;
if ($EVAL) {
    print "$VAR=@P;export $VAR";
}
else {
    print "@P";
}

__END__

=head1 NAME

splicepath - Returns a string with the spliced PATH

=head1 SYNOPSIS

  $ eval `splicepath -v PERL5LIB -o 0 -l 1 ~/src/perl/Parse-Eyapp-1.11
+3/lib`

=head1 DESCRIPTION

Works like Perl splice but with environment variables that follow
the C<:> separation convention (like C<PATH> or C<PERL5LIB>)

The mening of the options are as follows:

=over 2

=item *  C<-variable>

The environment variable (by default C<PATH>)

=item * C<-offset #number>

The offset. Like in Perl C<splice>

=item * C<-length #number>

The length. Like in Perl C<splice>

=item * C<-executable scriptname>

The script C<scriptname> will be executed and
the lines of its output  inserted in the variable

=item *  C<-bashsource>

True by default. The output is bash source to set the environment
variable

=back

=head1 EXAMPLES

Assuming the path:

  $ echo $PATH
  .:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/
+games

The command

  $ splicepath -o 2 -l 1 ~/bin

produces the output:

  PATH=.:/usr/local/sbin:/home/username/bin:/usr/sbin:/usr/bin:/sbin:/
+bin:/usr/games;export PATH

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others chilling in the Monastery: (6)
As of 2024-04-25 09:30 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found