#!/usr/bin/perl use warnings; use strict; my $usage = "merge_bed.pl "; my $input_1 = shift or die $usage; my $input_2 = shift or die $usage; my $output = shift or die $usage; open my $in1, "<", "$input_1" or die "Cannot open $input_1: $!\n"; open my $in2, "<", "$input_2" or die "Cannot open $input_2: $!\n"; open my $out, ">", "$output" or die "Cannot open $output: $!\n"; my %bed_files = (); while ( <$in1> ) { chomp; my ($chrom, $start, $end, undef, undef, $strand) = split "\t"; $bed_files{$chrom}{$start}[0] = $end; # you can save multiple values as an array, so both the end and strand and anything else you want $bed_files{$chrom}{$start}[1] = $strand; } while ( <$in2> ) { chomp; my ($chrom, $start, $end, undef, undef, $strand) = split "\t"; $bed_files{$chrom}{$start}[0] = $end; $bed_files{$chrom}{$start}[1] = $strand; } for my $chrom (sort keys %bed_files) { for my $start (sort {$a <=> $b} keys %{$bed_files[$chrom}}) { # print out the results sorted by chromosome (or scaffold) and start site print $out "$chrom\t$start\t$bed_files{$chrom}{$start}[0]\t$bed_files{$chrom}{$start}[1]\n"; } } close $in1; close $in2; close $out; exit;