Weighted Hardy's inequalities and the variational problem with compact perturbations