Let $n_{\gamma}(p,\theta)$ be the number of times the line parametrized by $(p,\theta)$ intersects the curve $\gamma$. Now suppose the path $\gamma$ is actually two nonintersecting curves put together, i.e. $\alpha\cup\beta$. Then $n_{\gamma}=n_{\alpha}+n_{\beta}.$ This is just basic counting: the number of times a line intersects $\alpha\cup\beta$ is equal to the number of times it intersects $\alpha$ plus the number of times it intersects $\beta$. Generalizing, if we have a square with four sides labelled $\alpha,\beta,\gamma,\delta$ (let's say each is open at one endpoint and closed at the other so they don't technically intersect), then the integral splits into $\iint n_\alpha dpd\theta+\iint n_\beta dpd\theta+\iint n_\gamma dpd\theta+\iint n_\delta dpd\theta.$ Now a curve's measure is invariant with respect to affine transformations, or rigid motions (this means the length of a curve is unchanged if you move, rotate, or reflect it). Thus for last three sides of the square we can perform a rigid motion in the plane that moves each one of them to simply occupy exactly the same line segment $\alpha$ occupies, so that the integral furthermore becomes $4\iint n_\alpha dpd\theta.$ Your first problem of evaluating the length of a line is already resolved, so the above is $4\times\text{ side length}.$ This is obviously the perimeter, as expected.
Suppose we want to set up the integral for the square concretely. Every line that intersects the square will intersect it exactly twice (except at some endpoints, but this will be a set of measure zero and so can be neglected). The only question is: for a given $\theta$, what values of $p$ imply that the line will go through the square? By symmetry, we'll only look at $\pi/4\le\theta\le\pi/2$ and multiply by $8$ in the end.
$\hskip 1.8in $ 
The maximum value $p$ can take for a given $\theta$ is the the base of the displayed right triangle above. But $\cos(\theta-\pi/4)=p/\text{hypotenuse}$, and that hypotenuse is $\sqrt{1/2^2+1/2^2}=1/\sqrt{2}$, so we solve for the base length $p=\cos(\theta-\pi/4)/\sqrt{2}$. Thus our formula becomes
$\frac{1}{2}\left(8\int_{\pi/4}^{\pi/2}\int_0^{\cos(\theta-\pi/4)/\sqrt{2}} 2dpd\theta\right) $ $=4 \int_{\pi/4}^{\pi/2}\frac{2}{\sqrt{2}}\cos(\theta-\pi/4)d\theta$ $=4\sqrt{2}\left(\sin(\pi/2-\pi/4)-\sin(\pi/4-\pi/4)\right)=4\sqrt{2}\left(\frac{1}{\sqrt{2}}-0\right)$ $=4.$ This is indeed the perimeter, as expected.